megengine.functional.nn.logsoftmax¶
- logsoftmax(inp, axis)[源代码]¶
对一个n维的输入张量做 \(\log(\text{softmax}(x))\) 函数 \(\text{logsoftmax}(x)\) 的公式可以简化为:
\[\text{logsoftmax}(x_{i}) = \log(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} )\]为了提高数值稳定性,实现根据以下的变换:
\[\text{logsoftmax}(x) = \log (\frac{\exp (x)}{\sum_{i}(\exp (x_{i}))}) = x - \log (\sum_{i}(\exp (x_{i}))) = x - \text{logsumexp}(x)\]实际案例
>>> import numpy as np >>> x = Tensor(np.arange(-5, 5, dtype=np.float32)).reshape(2,5) >>> y = F.logsoftmax(x, axis=1) >>> y.numpy().round(decimals=4) array([[-4.4519, -3.4519, -2.4519, -1.4519, -0.4519], [-4.4519, -3.4519, -2.4519, -1.4519, -0.4519]], dtype=float32)
- 返回类型