Flux.jl/src/onehot.jl

39 lines
1.2 KiB
Julia
Raw Normal View History

2017-09-06 22:58:55 +00:00
struct OneHotVector <: AbstractVector{Bool}
ix::UInt32
of::UInt32
end
Base.size(xs::OneHotVector) = (Int64(xs.of),)
Base.getindex(xs::OneHotVector, i::Integer) = i == xs.ix
Base.:*(A::AbstractMatrix, b::OneHotVector) = A[:, b.ix]
2017-09-27 20:58:34 +00:00
struct OneHotMatrix{A<:AbstractVector{OneHotVector}} <: AbstractMatrix{Bool}
data::A
2017-09-06 22:58:55 +00:00
end
Base.size(xs::OneHotMatrix) = (Int64(length(xs.data[1])),length(xs.data))
Base.getindex(xs::OneHotMatrix, i::Int, j::Int) = xs.data[j][i]
Base.:*(A::AbstractMatrix, B::OneHotMatrix) = A[:, map(x->x.ix, B.data)]
Base.hcat(x::OneHotVector, xs::OneHotVector...) = OneHotMatrix([x, xs...])
2017-09-27 20:58:34 +00:00
@require CuArrays begin
2017-09-27 21:51:00 +00:00
import CuArrays: CuArray, cudaconvert
2017-09-27 20:58:34 +00:00
CuArrays.cu(xs::OneHotMatrix) = OneHotMatrix(CuArrays.cu(xs.data))
2017-09-27 21:51:00 +00:00
Base.Broadcast._containertype(::Type{<:OneHotMatrix{<:CuArray}}) = CuArray
cudaconvert(x::OneHotMatrix{<:CuArray}) = OneHotMatrix(cudaconvert(x.data))
2017-09-27 20:58:34 +00:00
end
2017-09-06 22:58:55 +00:00
onehot(l, labels) = OneHotVector(findfirst(labels, l), length(labels))
onehotbatch(ls, labels) = OneHotMatrix([onehot(l, labels) for l in ls])
2017-09-11 12:40:11 +00:00
argmax(y::AbstractVector, labels = 1:length(y)) =
2017-09-06 22:58:55 +00:00
labels[findfirst(y, maximum(y))]
2017-09-11 12:40:11 +00:00
argmax(y::AbstractMatrix, l...) =
squeeze(mapslices(y -> argmax(y, l...), y, 1), 1)