scipy.special.softmax¶
- scipy.special.softmax(x, axis=None)[源代码]¶
SoftMax功能
Softmax函数通过计算每个元素的指数除以所有元素的指数和来转换集合中的每个元素。也就是说,如果 x 是一维数字数组::
softmax(x) = np.exp(x)/sum(np.exp(x))
- 参数
- xarray_like
输入数组。
- axis整型或整型元组,可选
轴以沿其计算值。默认值为None,将计算整个阵列的Softmax x 。
- 退货
- 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}}\]1.2.0 新版功能.
示例
>>> 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.0000000000000002
沿第一个轴(即柱)计算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.])