10 SoftMax函数

SoftMax函数:

参考链接:https://zhuanlan.zhihu.com/p/105722023

1 定义:

Softmax 的核心在于 soft,而 soft 有软的含义,与之相对的是 hard 硬。很多场景中需要我们找出数组所有元素中值最大的元素,实质上都是求的 hardmax 。下面使用 Numpy 模块以及 Pytorch 深度学习框架实现 hardmax。

# Numpy:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
a_max = np.max(a)
print(a_max)

# Pytorch:
import torch
a = torch.tensor([1, 2, 3, 4, 5])
a_max = torch.max(a)
print(a_max)

Softmax 函数即将各个输出节点的输出值范围映射到[0, 1],并且约束各个输出节点的输出值的和为1的函数。

\[\operatorname{Softmax}\left(z_{i}\right)=\frac{e^{z_{i}}}{\sum_{c=1}^{C} e^{z_{c}}} \]

可以看到,在这里引入了指数函数,我们先尝试不使用指数函数的做法:

\[\operatorname{Softmax}\left(z_{i}\right)=\frac{z_{i}}{\sum_{c=1}^{C} z_{c}} \]

# 不使用指数函数:
import torch

a = torch.FloatTensor([1, 2, 3, 4, 5])
a_sum = torch.sum(a)
a_softmax = a/a_sum
print(a_softmax)

Output:
tensor([0.0667, 0.1333, 0.2000, 0.2667, 0.3333], device='cpu')

# 使用指数函数:
class torch.nn.Softmax(input, dim)
# dim:指明维度,dim=0 表示按 列 计算;dim=1 表示按 行 计算。
# 一维使用 dim=1 报错
import torch

m1 = torch.nn.Softmax(dim = 0)
m2 = torch.nn.Softmax(dim = 1)
a = torch.FloatTensor([[1, 2, 3, 4, 5],[2, 3, 4, 5, 6]])
a_softmax1 = m1(a)
a_softmax2 = m2(a)
print('按列:\n', a_softmax1)
print('按行:\n', a_softmax2)

Output:
按列:
 tensor([[0.2689, 0.2689, 0.2689, 0.2689, 0.2689],
        [0.7311, 0.7311, 0.7311, 0.7311, 0.7311]], device='cpu')
按行:
 tensor([[0.0117, 0.0317, 0.0861, 0.2341, 0.6364],
        [0.0117, 0.0317, 0.0861, 0.2341, 0.6364]], device='cpu')

经过使用指数形式的 Softmax 函数能够将差距大的数值距离拉的更大。

posted @ 2021-10-28 12:26  SethDeng  阅读(91)  评论(0编辑  收藏  举报