scipy.special.
softmax#
- scipy.special.softmax(x, axis=None)[source]#
计算 softmax 函数。
softmax 函数通过计算每个元素的指数值除以所有元素指数值之和,来转换集合中的每个元素。 也就是说,如果 x 是一个一维 numpy 数组
softmax(x) = np.exp(x)/sum(np.exp(x))
- 参数:
- xarray_like
输入数组。
- axisint 或 ints 元组, 可选
计算值的轴。 默认为 None,softmax 将在整个数组 x 上计算。
- 返回:
- sndarray
与 x 形状相同的数组。 结果将沿指定轴求和为 1。
注释
向量 \(\sigma(x)\) 的 softmax 函数 \(x = \{x_0, x_1, ..., x_{n-1}\}\) 的公式为
\[\sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}}\]该实现使用移位来避免溢出。 更多详情请参见 [1]。
在版本 1.2.0 中添加。
除了 NumPy 之外,
softmax
还实验性地支持 Python Array API Standard 兼容后端。 请考虑通过设置环境变量SCIPY_ARRAY_API=1
并提供 CuPy、PyTorch、JAX 或 Dask 数组作为数组参数来测试这些功能。 支持以下后端和设备(或其他功能)的组合。库
CPU
GPU
NumPy
✅
不适用
CuPy
不适用
✅
PyTorch
✅
✅
JAX
✅
✅
Dask
✅
不适用
有关更多信息,请参见支持数组 API 标准。
参考文献
[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.])