Update: Should probably use StatsFuns.jl instead
This function exists in StatsFuns.jl (wish I had found that on my first search...). Their implementation is fancier and a little more efficient. Recommend going with theirs unless you really, really want to keep your dependencies small.
LogSumExp.jl
A Julia implementation of logsumexp.
LogSumExp.logsumexp โ Methodlogsumexp(a; dims=:)Computes the log-sum-exp. Mathematically equivalent to
log.(sum(exp.(a); dims=dims))but more numerically stable.
Note that, in keeping with the other Julia array operations, no dims are dropped in the output of logsumexp; instead,
size(logsumexp(a; dims=dims), d) == 1for each d in dims. For example:
julia> a = rand(2, 3, 4, 5);
julia> size(logsumexp(a; dims=(1,3)))
(1, 3, 1, 5)For a variant of logsumexp that does drop dims, see reduce_logsumexp.
LogSumExp.reduce_logsumexp โ Methodreduce_logsumexp(a; dims=:)Like logsumexp, but drops the dims dims in the output.
julia> a = rand(2, 3, 4, 5);
julia> size(reduce_logsumexp(a; dims=(1,3)))
(3, 5)