import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torchvision.datasets.MNIST(r"D:\365天深度学习100列\Pytorch实战 第P1周:实现mnist手写数字识别", train=True, transform=None, target_transform=None, download=True)
train_ds = torchvision.datasets.MNIST('data',
train=True,
transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
download=True)
test_ds = torchvision.datasets.MNIST('data',
train=False,
transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
download=True)
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_ds,
batch_size=batch_size,
shuffle=True)
test_dl = torch.utils.data.DataLoader(test_ds,
batch_size=batch_size)
imgs, labels = next(iter(train_dl))
print(imgs.shape)
import numpy as np
import torch.nn.functional as F
num_classes = 10 # 图片的类别数
class Model(nn.Module):
def __init__(self):
super().__init__()
# 特征提取网络
self.conv1 = nn.Conv2d(1, 32, kernel_size=3) # 第一层卷积,卷积核大小为3*3
self.pool1 = nn.MaxPool2d(2) # 设置池化层,池化核大小为2*2
self.conv2 = nn.Conv2d(32, 64, kernel_size=3) # 第二层卷积,卷积核大小为3*3
self.pool2 = nn.MaxPool2d(2)
# 分类网络
self.fc1 = nn.Linear(1600, 64)
self.fc2 = nn.Linear(64, num_classes)
# 前向传播
def forward(self, x):
x = self.pool1(F.relu(self.conv1(x)))
x = self.pool2(F.relu(self.conv2(x)))
x = torch.flatten(x, start_dim=1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
from torchinfo import summary
# 将模型转移到GPU中(我们模型运行均在GPU中进行)
model = Model().to(device)
summary(model)
# 三、 训练模型
# 1. 设置超参数
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
opt = torch.optim.SGD(model.parameters(),lr=learn_rate)
# 训练循环
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # 训练集的大小,一共60000张图片
num_batches = len(dataloader) # 批次数目,1875(60000/32)
train_loss, train_acc = 0, 0 # 初始化训练损失和正确率
for X, y in dataloader: # 获取图片及其标签
X, y = X.to(device), y.to(device)
# 计算预测误差
pred = model(X) # 网络输出
loss = loss_fn(pred, y) # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
# 反向传播
optimizer.zero_grad() # grad属性归零
loss.backward() # 反向传播
optimizer.step() # 每一步自动更新
# 记录acc与loss
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
train_acc /= size
train_loss /= num_batches
return train_acc, train_loss
def test (dataloader, model, loss_fn):
size = len(dataloader.dataset) # 测试集的大小,一共10000张图片
num_batches = len(dataloader) # 批次数目,313(10000/32=312.5,向上取整)
test_loss, test_acc = 0, 0
# 当不进行训练时,停止梯度更新,节省计算内存消耗
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
# 计算loss
target_pred = model(imgs)
loss = loss_fn(target_pred, target)
test_loss += loss.item()
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
test_acc /= size
test_loss /= num_batches
return test_acc, test_loss
epochs = 5
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(epochs):
model.train()
epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)
model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
train_acc.append(epoch_train_acc)
train_loss.append(epoch_train_loss)
test_acc.append(epoch_test_acc)
test_loss.append(epoch_test_loss)
template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
print('Done')
Output:
torch.Size([32, 1, 28, 28])
=================================================================
Layer (type:depth-idx) Param #
=================================================================
Model –
├─Conv2d: 1-1 320
├─MaxPool2d: 1-2 –
├─Conv2d: 1-3 18,496
├─MaxPool2d: 1-4 –
├─Linear: 1-5 102,464
├─Linear: 1-6 650
=================================================================
Total params: 121,930
Trainable params: 121,930
Non-trainable params: 0
=================================================================
Epoch: 1, Train_acc:76.6%, Train_loss:0.803, Test_acc:92.8%,Test_loss:0.245
Epoch: 2, Train_acc:94.3%, Train_loss:0.188, Test_acc:96.5%,Test_loss:0.121
Epoch: 3, Train_acc:96.3%, Train_loss:0.120, Test_acc:97.1%,Test_loss:0.095
Epoch: 4, Train_acc:97.2%, Train_loss:0.093, Test_acc:97.7%,Test_loss:0.078
Epoch: 5, Train_acc:97.6%, Train_loss:0.078, Test_acc:98.0%,Test_loss:0.061
Done
Repl Closed
直接替换交叉熵损失函数即可
loss_fn = CustomCrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
class CustomCrossEntropyLoss(torch.nn.Module):
def __init__(self):
super(CustomCrossEntropyLoss, self).__init__()
def forward(self, inputs, targets):
# 手动实现交叉熵损失函数
log_softmax = inputs.log_softmax(dim=1)
loss = -log_softmax[torch.arange(log_softmax.size(0)), targets].mean()
return loss
Output:
torch.Size([32, 1, 28, 28])
=================================================================
Layer (type:depth-idx) Param #
=================================================================
Model –
├─Conv2d: 1-1 320
├─MaxPool2d: 1-2 –
├─Conv2d: 1-3 18,496
├─MaxPool2d: 1-4 –
├─Linear: 1-5 102,464
├─Linear: 1-6 650
=================================================================
Total params: 121,930
Trainable params: 121,930
Non-trainable params: 0
=================================================================
Epoch: 1, Train_acc:80.1%, Train_loss:0.664, Test_acc:92.9%,Test_loss:0.239
Epoch: 2, Train_acc:94.6%, Train_loss:0.181, Test_acc:96.1%,Test_loss:0.128
Epoch: 3, Train_acc:96.5%, Train_loss:0.117, Test_acc:97.4%,Test_loss:0.082
Epoch: 4, Train_acc:97.2%, Train_loss:0.090, Test_acc:97.7%,Test_loss:0.075
Epoch: 5, Train_acc:97.7%, Train_loss:0.075, Test_acc:98.0%,Test_loss:0.063
Done
Repl Closed
对比官方所给交叉熵损失函数与自定义的损失函数,结果还是有轻微差别的。