Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update softmax with parameterization #16

Merged
merged 12 commits into from
Apr 21, 2021
11 changes: 5 additions & 6 deletions src/basicfuns.jl
Original file line number Diff line number Diff line change
Expand Up @@ -232,19 +232,18 @@ That is, `r` is overwritten with `exp.(x)`, normalized to sum to 1.

See the [Wikipedia entry](https://en.wikipedia.org/wiki/Softmax_function)
"""
function softmax!(r::AbstractArray{R}, x::AbstractArray{T}) where {R<:AbstractFloat,T<:Real}
function softmax!(r::AbstractArray{<:Real}, x::AbstractArray{<:Real})
n = length(x)
length(r) == n || throw(DimensionMismatch("Inconsistent array lengths."))
u = maximum(x)
s = 0.
s = zero(eltype(r))
@inbounds for i = 1:n
s += (r[i] = exp(x[i] - u))
end
invs = convert(R, inv(s))
@inbounds for i = 1:n
r[i] *= invs
r[i] /= s
end
r
return r
end

"""
Expand All @@ -261,4 +260,4 @@ $(SIGNATURES)
Return the [`softmax transformation`](https://en.wikipedia.org/wiki/Softmax_function)
applied to `x`.
"""
softmax(x::AbstractArray{<:Real}) = softmax!(similar(x, Float64), x)
softmax(x::AbstractArray{<:Real}) = softmax!(similar(x, float(eltype(x))), x)
17 changes: 16 additions & 1 deletion test/basicfuns.jl
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,22 @@ end
@testset "softmax" begin
x = [1.0, 2.0, 3.0]
r = exp.(x) ./ sum(exp.(x))
@test softmax([1.0, 2.0, 3.0]) ≈ r
@test softmax(x) ≈ r
softmax!(x)
@test x ≈ r

x = [1, 2, 3]
r = exp.(x) ./ sum(exp.(x))
@test softmax(x) ≈ r
@test eltype(softmax(x)) == Float64

x = [1//2, 2//3, 3//4]
r = exp.(x) ./ sum(exp.(x))
@test softmax(x) ≈ r
@test eltype(softmax(x)) == Float64

x = Float32[1, 2, 3]
r = exp.(x) ./ sum(exp.(x))
@test softmax(x) ≈ r
@test eltype(softmax(x)) == Float32
end