I searched "Mathematica LogSumExp", and literally nothing is coming up. It's a relatively important function in machine learning and for numerically stable computation. Will I just have to implement it myself?
1 Answer
$\begingroup$
$\endgroup$
3
I just made the answer for myself, since it's not too hard. Still, Mathematica really should provide a native implementation.
LogSumExp[x_] := With[{m = Max[x]}, m + Log[Total @ Exp[x - m]]];
The input x
has to be a list (e.g. x={1, 2, 3}
. The max stuff is to keep things numerically stable.
-
2$\begingroup$ It's probably neater to do
With[{m = Max[x]}, ...]
so you don't have to compute the Max twice $\endgroup$ Commented May 15, 2023 at 16:00 -
2$\begingroup$ Replace
Plus @@
withTotal @
and it will be faster, esp. on large data. $\endgroup$ Commented May 15, 2023 at 23:53 -
$\begingroup$ LogSumExp[x_] := Log[Total@Exp[x]] $\endgroup$ Commented Jun 2, 2023 at 12:48
Optimization`LogSumExp
. $\endgroup$