我有一个示例 python 批处理片段,我试图在 JuliaLang 中重新创建
softmax_outputs = np.array([[ 0.7, 0.1, 0.2 ],
[ 0.1, 0.5, 0.4 ],
[ 0.02, 0.9, 0.08]])
class_targets = [0, 1, 1]
print(softmax_outuputs[[0,1,2], class_targets])
>>>
[0.7 0.5 0.9]
Julia
softmax_outputs = [ 0.7 0.1 0.2
0.1 0.5 0.4
0.02 0.9 0.08]
class_targets = [1 2 2]
println(softmax_outputs[[1,2,3],class_targets])
[0.7; 0.1; 0.02]
[0.1; 0.5; 0.9]
[0.1; 0.5; 0.9]
julia>
最佳答案
您可以像这样使用 CartesianIndex
:
julia> softmax_outputs[CartesianIndex.([1, 2, 3], [1, 2, 2])]
3-element Vector{Float64}:
0.7
0.5
0.9
(请注意 [1, 2, 2]
是向量而不是您代码中的矩阵)
或者(假设你总是想索引整个范围)你可以写:
julia> getindex.(eachrow(softmax_outputs), [1, 2, 2])
3-element Vector{Float64}:
0.7
0.5
0.9
最后你可以使用理解(从 Python 移植时这可能是最自然的):
julia> [softmax_outputs[i, j] for (i, j) in zip([1, 2, 3], [1, 2, 2])]
3-element Vector{Float64}:
0.7
0.5
0.9
关于julia - 学习在 JuliaLang 中索引批处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68307675/