这节课也是课堂代码和课后作业分开更了~
我感觉这堂课内容还挺充实的,代码里需要注意或者补充的部分我都写了注释啦,大家不理解的地方可以看看有没有注释到~
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 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.l1 = torch.nn.Linear(784, 512) #28*28=784
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) #改变张量形状,变成二阶张量,-1自动计算出batch size
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) #此处不需要激活函数,直接接到softmax(计算损失的时候)
model = Net()
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) #带冲量
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('[epoch:%d, iteration:%5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300)) #每过300轮输出一次,%5d指定了输出字段宽度为5个字符,%.3f表示保留3位小数
running_loss = 0.0
def test(): #索引 batch_idx 用于控制训练过程中打印的频率,test 函数通常只在整个测试集上运行一次,只输出最终准确率
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
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()
结果: