首先定义几个必要的函数:
import torch
from matplotlib import pyplot as plt
def plot_curve(data):
fig = plt.figure()
plt.plot(range(len(data)), data, color='blue')
plt.legend(['value'], loc='upper right')
plt.xlabel('step')
plt.ylabel('value')
plt.show()
def plot_image(img, label, name):
fig = plt.figure()
for i in range(6):
plt.subplot(2, 3, i + 1)
plt.tight_layout()
plt.imshow(img[i][0]*0.3081+0.1307, cmap='gray', interpolation='none')
plt.title("{}: {}".format(name, label[i].item()))
plt.xticks([])
plt.yticks([])
plt.show()
def one_hot(label, depth=10):
out = torch.zeros(label.size(0), depth)
idx = torch.LongTensor(label).view(-1, 1)
out.scatter_(dim=1, index=idx, value=1)
return out
主程序:
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
import torchvision
from matplotlib import pyplot as plt
from utils import plot_curve, plot_image, one_hot
# step 1 load dataset
batch_size = 512 # 一次处理512张图片
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('mnist_data', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
# shuffle指家在数据的时候,随机打散,即打乱顺序
test_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('mnist_data/', train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=False)
# x, y = next(iter(train_loader))
# print(x.shape, y.shape)
# iter()函数是python的一个内置函数,用来生成一个迭代器;next()函数返回迭代器的下一个项目,next() 函数要和生成迭代器的 iter() 函数一起使用。
# # 得到的输出是:torch.Size([512, 1, 28, 28]) torch.Size([512]),指输入512张图片,1个通道 ,28行28列; label是512个
# print(x.min(), x.max()) # tensor(-0.4242) tensor(2.8215) normalize的结果 均值归一化 使数据分布在0的附近
# plot_image(x, y, 'image_sample')
class Net(nn.Module):
def __init__(self): # 定义网络层
super(Net, self).__init__()
# wx + b
self.fc1 = nn.Linear(28*28, 256)
self.fc2 = nn.Linear(256, 64)
self.fc3 = nn.Linear(64, 10)
def forward(self, x): # 定义前向传播
# x: [batch, 1, 28, 28]
x = F.relu(self.fc1(x)) # h1 = relu(xw1 + b1)
x = F.relu(self.fc2(x)) # h2 = relu(h1w2 + b2)
x = self.fc3(x) # h3 = h2w3 + b3
return x
net = Net() # 初始化一个网络
optimizer = optim.Adam(net.parameters(), lr=0.0001) # net.parameters()返回[w1, b1, w2, b2, w3, b3],即模型的参数
train_loss = []
for epoch in range(3): # 对数据集迭代三次
for batch_idx, (x, y) in enumerate(train_loader, 0): # 对数据集迭代一遍 每次迭代一个batch
'''
enumerate(iteration, start)函数默认包含两个参数,其中iteration参数为需要遍历的参数
比如字典、列表、元组等,start参数为开始的参数,默认为0(不写start那就是从0开始)
enumerate函数有两个返回值,第一个返回值为从start参数开始的数,第二个参数为iteration参数中的值。
'''
# x: [batch_size, 1, 28, 28] y:[batch_size]
x = x.view(x.size(0), 28*28) # 网络的输入,x,必须是[batch, feature]这样,所以需要转换x的shape,
# x.size(0)表示batch, 特征是28*28
out = net(x) # 得到一个[batch, 10]的输出
y_onehot = one_hot(y) # 使用onehot编码, 把y变成[batch, 10] 这样才能和呕吐进行比较 (使用loss)
loss = F.mse_loss(out, y_onehot) # loss 采用均值平方误差
optimizer.zero_grad() # 梯度清零
loss.backward() # 反向传播,即梯度计算过程
optimizer.step() # 上面计算了梯度,计算完需要更新w和b 即实现w'= w - lr*grad
train_loss.append(loss.item())
if batch_idx % 10 == 0:
print(epoch, batch_idx, loss.item())
# 跳出三次迭代 得到一个较好的[w1, b1, w2, b2, w3, b3]
plot_curve(train_loss)
total_correct = 0
for x, y in test_loader:
x = x.view(x.size(0), 28*28)
out = net(x)
pred = out.argmax(dim=1) # out: [batch, 10], 这一行返回这一个维度中间,值最大的索引 得到: [batch]
correct = pred.eq(y).sum().float().item() # 当前batch中 预测对的图片的总个数
total_correct += correct
total_num = len(test_loader.dataset)
acc = total_correct / total_num
print('test acc:', acc)
x, y = next(iter(test_loader))
out = net(x.view(x.size(0), 28*28))
pred = out.argmax(dim=1)
plot_image(x, pred, 'test')