- 🍨 本文为🔗365天深度学习训练营中的学习记录博客
- 🍖 原作者:K同学啊
一、配置环境
1. 创建虚拟环境torch:
conda create --name torch python=3.8
2. 激活虚拟环境torch:
conda activate torch
出现错误:
CondaError: Run 'conda init' before 'conda activate'
输入:
source activate base
再输入:
conda activate torch
成功!
3. 下载torch、torchvision、matplotlib
pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install torchvision -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
4. 下载ipython 使得可以单元格运行
pip install ipython
二、代码
#%% 加载需要的包
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
import numpy as np
import torch.nn.functional as F
from torchinfo import summary
from datetime import datetime
#%% 设置GPU和数据
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
train_ds = torchvision.datasets.MNIST('data', train=True, transform=torchvision.transforms.ToTensor(), download=False)
test_ds = torchvision.datasets.MNIST('data', train=False, transform=torchvision.transforms.ToTensor(), download=False)
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))
imgs.shape
#%% 画出部分训练数据
plt.figure(figsize=(20,5))
for i, imgs in enumerate(imgs[:20]):
npimg = np.squeeze(imgs.numpy())
plt.subplot(2,10,i+1)
plt.imshow(npimg, cmap=plt.cm.binary)
plt.axis('off')
plt.show()
#%% 构建网络架构
num_classes = 10
class Model(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
self.pool1 = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(32, 64, kernel_size=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
model = Model().to(device)
summary(model)
#%% 设置损失函数,学习率,优化器
loss_fn = nn.CrossEntropyLoss()
lr = 1e-2
opt = torch.optim.SGD(model.parameters(), lr=lr)
#%% 编写训练函数和测试函数
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
num_batches = len(dataloader)
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)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss += loss.item()
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss /= num_batches
train_acc /= size
return train_acc, train_loss
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_loss, test_acc = 0, 0
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
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)
print(f'Epoch:{epoch+1}, Train_acc:{epoch_train_acc * 100:.2f}%, Train_loss:{epoch_train_loss},Test_acc:{epoch_test_acc * 100:.2f}%, Test_loss:{epoch_test_loss}')
print('Done')
#%% 结果可视化
current_time = datetime.now()
epoch_range = range(epochs)
plt.figure(figsize=(12,3))
plt.subplot(1, 2, 1)
plt.plot(epoch_range, train_acc, label='Training accuracy')
plt.plot(epoch_range, test_acc, label='Test accuracy')
plt.legend(loc = 'lower right')
plt.title('Training and Validation accuracy')
plt.xlabel(current_time)
plt.subplot(1, 2, 2)
plt.plot(epoch_range, train_loss, label='Training loss')
plt.plot(epoch_range, test_loss, label='Test loss')
plt.legend(loc = 'upper right')
plt.title('Training and Validation loss')
plt.xlabel(current_time)
plt.show()