《PyTorch深度学习实践》完结合集_哔哩哔哩_bilibili
Softmax Classifer
1、二分类问题:糖尿病预测
2、多分类问题
MNIST Dataset:10个标签,图像数字(0-9)识别
①用sigmoid:输出每个类别的概率
但这种情况下,类别之间所存在的互相抑制的关系没有办法体现,当一个类别出现的概率较高时,其他类别出现的概率仍然有可能很高。
换言之,当计算输出为1的概率之后,再计算输出为2的概率时,并不是在输出为非1的条件下进行的,也就是说,所有输出的概率之和实际上是大于1的。
②用softmax:输出每个类别的概率的分布
3、softmax原理
保证两点:
※每个类别概率都>0------指数函数
※所有类别概率相加为1------求和,占比
4、Softmax Loss Function
①NLLLoss
②Torch.nn.CrossEntropyLoss()中包含了最后一层的softmax激活
③交叉熵损失(CrossEntropyLoss)和NLL损失之间的差别
5、实例:MNIST Dataset
①数据准备
transform将图像转换成图像张量(CxWxH)(通道x宽x高),取值在[0,1]
再进行标准化
## 将图像数据转换成图像张量 transform = transforms.Compose([ transforms.ToTensor(), # 标准化,均值和标准差 transforms.Normalize((0.1307,), (0.3081,)) ])
②模型构建
完整代码
# -*- coding: utf-8 -*- """ Created on Wed Aug 4 09:08:32 2021 @author: motoh """ import torch ## 对图像数据进行处理的包 from torchvision import transforms from torchvision import datasets from torch.utils.data import DataLoader import torch.nn.functional as F import torch.optim as optim # prepare dataset batch_size = 64 ## 将图像数据转换成图像张量 # 标准化,均值和标准差 transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) train_dataset = datasets.MNIST(root=‘../dataset/mnist/‘, train=True, download=True, transform=transform) train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size) test_dataset = datasets.MNIST(root=‘../dataset/mnist/‘, train=False, download=True, transform=transform) test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size) # design model using class class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.l1 = torch.nn.Linear(784, 512) self.l2 = torch.nn.Linear(512, 256) self.l3 = torch.nn.Linear(256, 128) self.l4 = torch.nn.Linear(128, 64) self.l5 = torch.nn.Linear(64, 10) def forward(self, x): #变成矩阵 -1其实就是自动获取mini_batch,784是1*28*28,图片的像素数量 x = x.view(-1, 784) x = F.relu(self.l1(x)) x = F.relu(self.l2(x)) x = F.relu(self.l3(x)) x = F.relu(self.l4(x)) # 最后一层不做激活,不进行非线性变换 return self.l5(x) model = Net() # construct loss and optimizer criterion = torch.nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) # training cycle forward, backward, update def train(epoch): running_loss = 0.0 for batch_idx, data in enumerate(train_loader, 0): # 获得一个批次的数据和标签 inputs, target = data optimizer.zero_grad() # 获得模型预测结果(64, 10) outputs = model(inputs) # 交叉熵代价函数outputs(64,10),target(64) loss = criterion(outputs, target) loss.backward() optimizer.step() running_loss += loss.item() if batch_idx % 300 == 299: print(‘[%d, %5d] loss: %.3f‘ % (epoch+1, batch_idx+1, running_loss/300)) running_loss = 0.0 def test(): correct = 0 total = 0 ## 不计算梯度 with torch.no_grad(): for data in test_loader: images, labels = data outputs = model(images) # dim = 1 列是第0个维度,行是第1个维度,## 每一行最大值的下标 _, predicted = torch.max(outputs.data, dim=1) total += labels.size(0) correct += (predicted == labels).sum().item() # 张量之间的比较运算 print(‘accuracy on test set: %d %% ‘ % (100*correct/total)) if __name__ == ‘__main__‘: for epoch in range(10): train(epoch) test()