scipy.special.

softmax#

scipy.special.softmax(x, axis=None)[源代码][源代码]#

计算 softmax 函数。

softmax 函数通过计算每个元素的指数除以所有元素指数之和来转换集合中的每个元素。也就是说,如果 x 是一个一维的 numpy 数组:

softmax(x) = np.exp(x)/sum(np.exp(x))
参数:
xarray_like

输入数组。

int 或 int 的元组,可选

要计算值的轴。默认值为 None,将在整个数组 x 上计算 softmax。

返回:
sndarray

x 形状相同的数组。结果将沿指定轴求和为 1。

注释

softmax 函数的公式 \(\sigma(x)\) 对于向量 \(x = \{x_0, x_1, ..., x_{n-1}\}\)

\[\sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}}\]

softmax 函数是 logsumexp 的梯度。

该实现使用移位来避免溢出。更多细节请参见 [1]

Added in version 1.2.0.

参考文献

[1]

P. Blanchard, D.J. Higham, N.J. Higham, “Accurately computing the log-sum-exp and softmax functions”, IMA Journal of Numerical Analysis, Vol.41(4), DOI:10.1093/imanum/draa038.

示例

>>> import numpy as np
>>> from scipy.special import softmax
>>> np.set_printoptions(precision=5)
>>> x = np.array([[1, 0.5, 0.2, 3],
...               [1,  -1,   7, 3],
...               [2,  12,  13, 3]])
...

在整个数组上计算 softmax 变换。

>>> m = softmax(x)
>>> m
array([[  4.48309e-06,   2.71913e-06,   2.01438e-06,   3.31258e-05],
       [  4.48309e-06,   6.06720e-07,   1.80861e-03,   3.31258e-05],
       [  1.21863e-05,   2.68421e-01,   7.29644e-01,   3.31258e-05]])
>>> m.sum()
1.0

沿第一个轴(即列)计算 softmax 变换。

>>> m = softmax(x, axis=0)
>>> m
array([[  2.11942e-01,   1.01300e-05,   2.75394e-06,   3.33333e-01],
       [  2.11942e-01,   2.26030e-06,   2.47262e-03,   3.33333e-01],
       [  5.76117e-01,   9.99988e-01,   9.97525e-01,   3.33333e-01]])
>>> m.sum(axis=0)
array([ 1.,  1.,  1.,  1.])

沿第二个轴(即行)计算 softmax 变换。

>>> m = softmax(x, axis=1)
>>> m
array([[  1.05877e-01,   6.42177e-02,   4.75736e-02,   7.82332e-01],
       [  2.42746e-03,   3.28521e-04,   9.79307e-01,   1.79366e-02],
       [  1.22094e-05,   2.68929e-01,   7.31025e-01,   3.31885e-05]])
>>> m.sum(axis=1)
array([ 1.,  1.,  1.])