maxframe.tensor.special.softmax#

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

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

softmax(x) = np.exp(x)/sum(np.exp(x))
参数:
  • x (array_like) -- 输入数组。

  • axis (int or tuple of ints, optional) -- 计算值所沿的轴。默认为 None,此时将在整个数组 x 上计算 softmax。

返回:

s -- 与 x 形状相同的数组。结果在指定轴上的总和为 1。

返回类型:

ndarray

备注

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

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

softmax 函数是 logsumexp 的梯度。

该实现使用偏移来避免溢出。详见 [1]

引用

示例

>>> import maxframe.tensor as mt
>>> from maxframe.tensor.special import softmax
>>> x = mt.array([[1, 0.5, 0.2, 3],
...               [1,  -1,   7, 3],
...               [2,  12,  13, 3]])
...

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

>>> m = softmax(x)
>>> m.to_numpy()
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().to_numpy()
1.0

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

>>> m = softmax(x, axis=0)
>>> m.to_numpy()
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).to_numpy()
array([ 1.,  1.,  1.,  1.])

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

>>> m = softmax(x, axis=1)
>>> m.to_numpy()
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).to_numpy()
array([ 1.,  1.,  1.])