【Pytorch神经网络理论篇】 08 Softmax函数(处理分类问题)

1.1 Softmax函数简介

oftmax函数本质也为激活函数,主要用于多分类问题,且要求分类互斥,分类器最后的输出单元需要Softmax 函数进行数值处理。

Tip:在搭建网络模型的时候,需要用Softmax将目标分成几个,则在最后一层放几个节点

1.1.1Softmax函数构成

C为:分类的类别数

1.1.2 Softmax傻瓜式解释

将所有的值用e的n次方计算出来,求和之后计算每一个值的占比,保证其和为100%,即为概率

Tip:若多分类任务中的每个类之间不是互斥,则将其转化为多个二分类来组成

1.2 Softmax函数的原理剖析

1.3 Softmax代码部分

1.3.1 常用的Softmax结构

torch.nn.Softmax(dim) 计算Softmax,参数代表计算维度
torch.nn.Softmax2d() 对每个图片进行Softmax处理
torch.nn.LogSoftmax(logits,name=None) 对Softmax取对数,常与NULLLoss联合使用,实现交叉熵损失的计算

1.3.2 Softmax代码实现

import torch

#定义模拟数据
# logits:神经网络的计算结果,一共两个数据,每个数据的结果中包括三个数值,其为三个分类的结果
logits = torch.autograd.Variable(torch.tensor([[2,0.5,6],[0.1,0,3]]))
# labels:神经网络的计算结果对应的标签,每个数值代表一个数据分类的编号,且相互互斥
labels = torch.autograd.Variable(torch.LongTensor([2,1]))
print(logits)
# 输出 tensor([[2.0000, 0.5000, 6.0000],[0.1000, 0.0000, 3.0000]])
print(labels)
# 输出 tensor([2, 1])

#计算 Softmax
print('Softmax:',torch.nn.Softmax(dim=1)(logits))
# 输出 Softmax: tensor([[0.0179, 0.0040, 0.9781],[0.0498, 0.0451, 0.9051]])

### LogSoftmax() + NULLoss() = CrossEntropyLoss()
#计算 LogSoftmax:对Softmax取对数
logsoftmax = torch.nn.LogSoftmax(dim=1)(logits)
print('LogSoftmax:',logsoftmax)
# 输出 LogSoftmax: tensor([[-4.0222, -5.5222, -0.0222],[-2.9997, -3.0997, -0.0997]])
#计算 NULLoss
output = torch.nn.NLLLoss()(logsoftmax,labels)
print('NULLoss:',output)
# 输出 NULLoss: tensor(1.5609)

#计算 CrossEntropyLoss
CrossEntropyLoss_return = torch.nn.CrossEntropyLoss()(logits,labels)
print('CrossEntropyLoss:',CrossEntropyLoss_return)
# 输出 CrossEntropyLoss: tensor(1.5609)

猜你喜欢

转载自blog.csdn.net/qq_39237205/article/details/123340482#comments_22116800