我在神经网络的最后一层使用Softmax激活函数.但我在安全实现此功能时遇到问题.
一个天真的实现将是这个:
Vector y = mlp(x); // output of the neural network without softmax activation function
for(int f = 0; f < y.rows(); f++)
y(f) = exp(y(f));
y /= y.sum();
Run Code Online (Sandbox Code Playgroud)
对于> 100个隐藏节点,这不能很好地工作,因为y NaN在很多情况下(如果y(f)> 709,exp(y(f))将返回inf).我想出了这个版本:
Vector y = mlp(x); // output of the neural network without softmax activation function
for(int f = 0; f < y.rows(); f++)
y(f) = safeExp(y(f), y.rows());
y /= y.sum();
Run Code Online (Sandbox Code Playgroud)
在哪里safeExp定义为
double safeExp(double x, int div)
{
static const double maxX = …Run Code Online (Sandbox Code Playgroud)