Given a vector of indices I want to get a matrix where only one element with corresponding index is one and others are zeros. On CPU it’s pretty easy, e.g.:
function onehot(s::AbstractVector, n_dims::Int=maximum(s))
x = zeros(Int, n_dims, length(s))
for (j, i) in enumerate(s)
x[i, j] = 1
end
return x
end
julia> onehot([1, 2, 3, 4])
4×4 Array{Int64,2}:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
But for GPU it’s not very efficient technique. Are there any better alternatives?