Skip to content

Commit

Permalink
Merge pull request #130 from merckxiaan/master
Browse files Browse the repository at this point in the history
Make softmax! dimension-agnostic
  • Loading branch information
MikeInnes authored Jul 8, 2019
2 parents 4ea355e + 16262e8 commit 342928e
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/softmax.jl
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ independent.
0.244728
0.665241
"""
softmax(xs) = softmax!(similar(xs), xs)
function softmax(xs::AbstractArray{T}; dims=1) where {T}
max = maximum(xs, dims=dims)
out = exp.(xs .- max) ./ sum(exp.(xs .- max), dims=dims)
end

function softmax!(out::AbstractVecOrMat{T}, xs::AbstractVecOrMat{T}) where {T}
@inbounds for j = 1:size(xs, 2)
Expand Down Expand Up @@ -50,8 +53,10 @@ function ∇softmax!(out::AbstractVecOrMat, Δ::AbstractVecOrMat, xs::AbstractVe
sf = softmax(xs)
out .= sf .*.- sum.*sf, dims = 1))
end

∇softmax(Δ, xs) = ∇softmax!(similar(Δ), Δ, xs)
function ∇softmax(Δ, xs; dims=1)
sf = softmax(xs, dims=dims)
out = sf .*.- sum.* sf, dims=dims))
end
∇softmax!(Δ, xs) = ∇softmax!(Δ, Δ, xs)


Expand Down

0 comments on commit 342928e

Please sign in to comment.