learning to index batches in JuliaLang

Viewed 37

I have a example python batch processing snippet that I am attempting to recreate in 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>
1 Answers

You can use CartesianIndex like this:

julia> softmax_outputs[CartesianIndex.([1, 2, 3], [1, 2, 2])]
3-element Vector{Float64}:
 0.7
 0.5
 0.9

(note that [1, 2, 2] is vector not a matrix like in your code)

Alternatively (assuming you always want to index the whole range) you can write:

julia> getindex.(eachrow(softmax_outputs), [1, 2, 2])
3-element Vector{Float64}:
 0.7
 0.5
 0.9

Finally you could use a comprehension (which is probably most natural when porting from 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
Related