Softmax 函数

December 16, 2023

有什么作用?

Softmax 也叫 softargmax 或归一化指数函数。它把一个包含 K 个实数的向量转换为 K 种可能结果的概率分布。

softmax_demo1alt

如何计算?

softmax_demo0alt

softmax_demo2alt

实现时要注意什么?

输入很大时,计算 e^x 可能会超出数值类型的表示范围。 一个简单的办法是先从每个 x 中减去所有输入中的最大值。

Softmax 和 argmax

argmax 的局限

argmax 返回输入数组中最大值的索引。

例如,写成独热向量就是 argmax( [0.25, 1.23, -0.8] ) -> [0,1,0]。

直接使用 argmax 有个局限:神经网络原始输出稍有变化时,返回的索引通常不变,因此几乎处处梯度为零。而神经网络正是靠梯度反向传播来学习的。

Softmax 的好处

从 e^x 的函数图像可以看到,不论输入 x 是正数、负数还是零,e^x 始终为正。

对向量 z 应用 softmax,可以分两步:

1. 对每个元素取指数。
2. 将每个结果除以所有元素的指数之和。

为什么要用 softmax 这样的激活函数?把每个输出除以所有输出之和不行吗?

我们用几个例子来看看。

下面这个函数返回除以总和后的数组。

def div_by_sum(z):
  sum_z = np.sum(z)
  out_z = np.round(z/sum_z,3)
  return out_z

对 z1 = [0.25, 1.23, -0.8] 调用 div_by_sum。结果之和虽然是 1,但里面既有正数也有负数,仍然不能将每个值解释为概率。

z1 = [0.25,1.23,-0.8]
div_by_sum(z1)
array([ 0.368,  1.809, -1.176])

再看 z2 = [-0.25, 1, -0.75]。各元素之和为零,分母也就为零。用总和做归一化会遇到运行时警告,因为除以零没有定义。

z2 = [-0.25,1,-0.75]
div_by_sum(z2)
RuntimeWarning: divide by zero encountered in true_divide
array([-inf,  inf, -inf])

再取 z4 = [0, 0.9, 0.1],对比 softmax 与直接归一化的结果。

z4 = [0,0.9,0.1]
print(div_by_sum(z4))
print(softmax(z4))
[0.  0.9 0.1] # normalized
[0.219 0.539 0.242] # softmax

这里需要留意零值对学习的影响:如果某个输入为零,相应权重从这项输入得到的梯度贡献也会是零。

从这个角度看,softmax 激活可以看成对 argmax 的平滑近似。

N = 2 时 sigmoid 与 softmax 的等价性

对于二分类,两类的 softmax 可以用 sigmoid 等价地表示。

损失函数

与其他分类任务一样,这里通常使用交叉熵损失。

参考资料

  1. Kiprono Elijah Koech. (Sep 30, 2020). Softmax Activation Function — How It Actually Works [Blog post]. Towards Data Science. Retrieved from https://towardsdatascience.com/softmax-activation-function-how-it-actually-works-d292d335bd78

  2. Bala Priya C. (Jun 30, 2023). Softmax Activation Function: Everything You Need to Know [Blog post]. Pinecone. Retrieved from https://www.pinecone.io/learn/softmax-activation/

  3. Softmax function. (12 February 2024). In Wikipedia. Retrieved Mar 15, 2024, from https://en.wikipedia.org/wiki/Multi-agent_system

延伸阅读

  1. PP鲁. (Aug 05, 2020). 三分钟读懂Softmax函数. 知乎专栏. [Blog post]. Retrieved from https://zhuanlan.zhihu.com/p/168562182

  2. 触摸壹缕阳光. (Feb 10, 2020). 一文详解Softmax函数. 知乎专栏. [Blog post]. Retrieved from https://zhuanlan.zhihu.com/p/105722023

© 2023 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2023-12-16). Softmax 函数. https://caiborui.com/blog/2023-12-16-en-softmax-function-zhtrans

@misc{borui2023-ca2192d5,
  author = {borui},
  title = {{Softmax 函数}},
  year = {2023},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2023-12-16-en-softmax-function-zhtrans}
}