一、课堂代码&课后作业
这次的整个代码和上节课差不多,就是把model换成cnn了,作业也是继续修改模型,所以我这里就直接做作业啦,Tensor维度的变化我也注释在模型旁边了,大家可以参考一下自行修改~
import torch
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F #用relu
import torch.optim as optim
import matplotlib.pyplot as plt
import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib.request.install_opener(opener)
batch_size = 64
transform = transforms.Compose([
transforms.ToTensor(), #将图像转为tensor,w*h*c → c*w*h, [0,255] → [0,1]
transforms.Normalize((0.1307, ), (0.3081, )) # 数据集的均值mean,标准差std
])
train_dataset = datasets.MNIST(root='./datasets/mnist/',
train=True,
transform=transform,
download=True)
train_loader = DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True)
test_dataset = datasets.MNIST(root='./datasets/mnist/',
train=False,
transform=transform,
download=True)
test_loader = DataLoader(test_dataset,
batch_size=batch_size,
shuffle=False)
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5) #1*28*28 → 10*24*24 → 10*12*12
self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=3, padding=1) #10*12*12 → 20*12*12 → 20*6*6
self.conv3 = torch.nn.Conv2d(20, 40, kernel_size=3, padding=1) #20*6*6 → 40*6*6 → 40*3*3
self.pooling = torch.nn.MaxPool2d(2)
self.fc1 = torch.nn.Linear(360, 180)
self.fc2 = torch.nn.Linear(180, 10)
def forward(self, x):
batch_size = x.size(0)
x = F.relu(self.pooling(self.conv1(x)))
x = F.relu(self.pooling(self.conv2(x)))
x = F.relu(self.pooling(self.conv3(x)))
x = x.view(batch_size, -1) #flatten
x = self.fc1(x)
return self.fc2(x) #此处不需要激活函数,直接接到softmax(计算损失的时候)
model = Net()
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model.to(device)
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) #带冲量
epoch_list = []
loss_list = []
def train(epoch):
running_loss = 0.0
total_loss = 0.0
count = 0
for batch_idx, data in enumerate(train_loader, 0):
inputs, target = data
inputs, target = inputs.to(device), target.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, target)
total_loss += loss.item()
count += 1
loss.backward()
optimizer.step()
running_loss += loss.item()
if batch_idx % 300 == 299:
print('[epoch:%d, iteration:%5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300)) #每过300轮输出一次,%5d指定了输出字段宽度为5个字符,%.3f表示保留3位小数
running_loss = 0.0
epoch_list.append(epoch)
loss_list.append(total_loss/count)
def test(): #索引 batch_idx 用于控制训练过程中打印的频率,test 函数通常只在整个测试集上运行一次,只输出最终准确率
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images) #输出的是batch里每个样本的分布构成的矩阵
_, predicted = torch.max(outputs.data, dim=1) #沿着维度1(列)找最大值的下标,返回的是最大值及对应下标,因此前面用一个占位符
total += labels.size(0) #size就是(N, 1),取第0个元素就是N,其实就是累计测试集的总样本数
correct += (predicted == labels).sum().item() #对应位置比较,相同为1不同为0,再计算比较结果的总和
print('Accuracy on test set: %d %%' %(100*correct/total))
if __name__ == '__main__':
for epoch in range(10):
train(epoch)
test()
plt.plot(epoch_list, loss_list)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training Loss')
plt.savefig('cnn.png')
结果:
这张图画错了,我忘记给loss求均值,直接把总的loss输出了,所以loss很大
代码我已经改过了,图我就不重新画了,大差不差
测试集的accuracy忘记截图了,稳定在98%