B站刘二大人老师的《PyTorch深度学习实践》Lecture_09 重点回顾+代码复现
Lecture_09 多分类问题 Softmax Classifier
一、重点回顾
(一)Softmax Layer
通过softmax层,使得各项输出>0,且和为1。
softmax层的计算如下:
举个例子:
(二)Loss Function - Cross Entropy
Cross Entropy in Numpy:
import numpy as np
y = np.array([1,0,0])
z = np.array([0.2,0.1,-0.1])
y_pred = np.exp(z)/np.exp(z).sum()
loss = (-y*np.log(y_pred)).sum()
print(loss)
Cross Entropy in PyTorch:
import torch
y = torch.LongTensor([0])
z = torch.Tensor([[0.2,0.1,-0.1]])
criterion = torch.nn.CrossEntropyLoss()
loss = criterion(z,y)
print(loss)
这里不需要再加激活函数!!!
CrossEntropyLoss vs NLLLoss
This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class.
(三)MNIST Dataset
手写数字集,每个图象为28*28=784个像素。
进行神经网络训练时,希望的数据在0到1之间,并且符合正态分布,所以需要将数据集进行以下转变:
transform = transforms.Compose([
transforms.ToTensor(), # Convert the PIL Image to Tensor
transforms.Normalize((0.1307,),(0.3081,)) # 均值和标准差
])
二、代码复现
# Import Package
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(), # Convert the PIL Image to Tensor
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(train_dataset,shuffle=False,batch_size=batch_size)
# Design Model
class Net(torch.nn.Module):
"""docstring for Net"""
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):
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)
# Train and Test
def train(epoch):
running_loss = 0.0
for batch_idx,data in enumerate(train_loader,0):
inputs,target = data
optimizer.zero_grad()
outputs = model(inputs)
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)
_,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()
如果下载数据集的时候很慢,找个网速好的地方就好了~
运行结果: