10 SoftMax函数

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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 函数能够将差距大的数值距离拉的更大。

脚本宝典总结

以上是脚本宝典为你收集整理的10 SoftMax函数全部内容,希望文章能够帮你解决10 SoftMax函数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: