众所周知第七章在复现各大神经网络的时候也会用到ch6定义的各种函数,为了方便理解其中的细节,在这里具体讲解一下!
目录
1.LeNet实现
1.1net搭建
这里使用Seq简单复现即可,没啥好说的。
注意:在Sequential里面也是可以写进自己的类的,详细见5_1。
nn.Flatten()是将张量拉成(bs,-1)维度的张量
注意最后送到全连接的input是需要自己算的!另外激活函数为Sigmoid
net = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Flatten(),
nn.Linear(16 * 5 * 5, 120), nn.Sigmoid(),
nn.Linear(120, 84), nn.Sigmoid(),
nn.Linear(84, 10))
X = torch.rand(size=(1, 1, 28, 28), dtype=torch.float32)
for layer in net:
X = layer(X)
print(layer.__class__.__name__,'output shape: \t',X.shape)
'''
Conv2d output shape: torch.Size([1, 6, 28, 28])
Sigmoid output shape: torch.Size([1, 6, 28, 28])
AvgPool2d output shape: torch.Size([1, 6, 14, 14])
Conv2d output shape: torch.Size([1, 16, 10, 10])
Sigmoid output shape: torch.Size([1, 16, 10, 10])
AvgPool2d output shape: torch.Size([1, 16, 5, 5])
Flatten output shape: torch.Size([1, 400])
Linear output shape: torch.Size([1, 120])
Sigmoid output shape: torch.Size([1, 120])
Linear output shape: torch.Size([1, 84])
Sigmoid output shape: torch.Size([1, 84])
Linear output shape: torch.Size([1, 10])
'''
简单用一个28的向量(与FM单张图片hw相同)看一下结构,注意卷积尺寸计算公式:
o=[(i+2p-k)/s]+1这个公式对应正方形尺寸图片卷积尺寸
1.2数据集改正
原始的num_works=4,这里笔者的电脑太拉,用4的话内存不够用,所以改成2(如果2还不行直接上0)
def load_data_fashion_mnist_nw2(batch_size, resize=None):
"""下载Fashion-MNIST数据集,然后将其加载到内存中"""
trans = [transforms.ToTensor()]
if resize:
trans.insert(0, transforms.Resize(resize))
trans = transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(
root="../data", train=True, transform=trans, download=True)
mnist_test = torchvision.datasets.FashionMNIST(
root="../data", train=False, transform=trans, download=True)
return (data.DataLoader(mnist_train, batch_size, shuffle=True,
num_workers=2),
data.DataLoader(mnist_test, batch_size, shuffle=False,
num_workers=2))
然后设置loader,注意这里要用上面该过nw的函数:
batch_size = 128
train_iter, test_iter = load_data_fashion_mnist_nw2(batch_size=batch_size)
1.3存储到gpu上的验证集
重头戏之一,存储到gpu上的验证!相关gpu的设置见ch5_5。
本质是使用gpu设置对evaluate_accuracy进行修改:
def evaluate_accuracy_gpu(net, data_iter, device=None): #@save
"""使⽤GPU计算模型在数据集上的精度"""
if isinstance(net, nn.Module):
net.eval() # 设置为评估模式
if not device:
device = next(iter(net.parameters())).device
'''正确预测的数量,总预测的数量'''
metric = d2l.Accumulator(2)
with torch.no_grad():
for X, y in data_iter:
if isinstance(X, list):
'''BERT微调所需的(之后将介绍)'''
X = [x.to(device) for x in X]
else:
X = X.to(device)
y = y.to(device)
metric.add(d2l.accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
开始的device=None,如果开始没有指定device,则看net里面的参数中的device是啥,然后设置成net参数里面的device,也是保证统一。
再将每个loader中的数据挪到device中,如果是个list那就每一个都挪,如果是tensor的话就挪一次。对应的y也要挪到gpu上,一般y都是tensor所以挪一次就好。
这里计算的时候用到了之前讲过的accuracy,在此再看一下,最后返回的是y_hat与y预测类别正确的数量。
def accuracy(y_hat, y): # @save
"""计算预测正确的数量"""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = y_hat.argmax(axis=1)
cmp = y_hat.type(y.dtype) == y
return float(cmp.type(y.dtype).sum())
在这里补充一下,经过了.argmax后,维度降成1维,每个元素代表每个图片的预测种类,与y一样
2.ch6训练
由于这个函数实在是太重要了,所以我直接把它设成标题1。
先上原版代码:首先是比ch3多了gpu设置。
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
"""⽤GPU训练模型(在第六章定义)"""
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
print('training on', device)
net.to(device)
optimizer = torch.optim.SGD(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss()
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
legend=['train loss', 'train acc', 'test acc'])
timer, num_batches = d2l.Timer(), len(train_iter)
for epoch in range(num_epochs):
# 训练损失之和,训练准确率之和,样本数
metric = d2l.Accumulator(3)
net.train()
for i, (X, y) in enumerate(train_iter):
timer.start()
optimizer.zero_grad()
X, y = X.to(device), y.to(device)
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
optimizer.step()
with torch.no_grad():
metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
timer.stop()
train_l = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1) / num_batches,
(train_l, train_acc, None))
test_acc = evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_acc))
print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
f'test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
f'on {str(device)}')
初始化weight,如果使用了全连接层或者卷积层,则用xavier初始化权重。
在此补充xavier作用:根据输入输出的大小,使得再用随机数的时候,各个随机数之间的方差是差不多的,保证模型开始的时候梯度炸掉或者变为0。
再将初始化权重部署到每一个layer中(.apply())
打印一下再那个地方训练,避免弄了半天还是再cpu上。再将整个net挪到gpu上。
添加了一个计时操作,每次计时的是每个epoch的训练用时。
并注意在训练时,要将loader里面的X,y挪到gpu上!
2.2loss探索
在此补充一下我的探索,因为我发现MLP的时候是用的l.mean().backward,而在这没有了,细看了一下,根源在于loss = nn.CrossEntropyLoss()里面有没有定义reduction='none'。
如上图,定义了reduction='none'后,表示loss计算不会降维,保存每一个bs中的损失,所以得到的l是(bs)的loss,所以后续计算反向梯度下降的时候要mean()求均值(保证是标量对向量求导),由于最后累加器累加每个iter的loss,所以将(bs)的loss使用.sum()进行加和。
而这次没有采用reduction='none'时,默认的时reduction='mean',直接在loss的时候就进行了均值操作。
如上图,loss计算后的l是一个标量,经过累加器后,均值*个数(bs)=l.sum(),由于权重是随机的,所以几乎等于上一个即可说明二者是相等同的!
所以往后直接不设置reduction好了,这样反向传播还简单一点。
2.3改编版显数函数
众所周之笔者感觉画图的东西太罗嗦,跟ch3一样整了一个每个epoch显示数值的版本出来:
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
"""⽤GPU训练模型(在第六章定义)"""
global train_l, train_acc, metric
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
print('training on', device)
net.to(device)
optimizer = torch.optim.SGD(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss()
# animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
# legend=['train loss', 'train acc', 'test acc'])
timer, num_batches = d2l.Timer(), len(train_iter)
for epoch in range(num_epochs):
# 训练损失之和,训练准确率之和,样本数
metric = d2l.Accumulator(3)
net.train()
for i, (X, y) in enumerate(train_iter):
timer.start()
optimizer.zero_grad()
X, y = X.to(device), y.to(device)
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
optimizer.step()
with torch.no_grad():
metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
timer.stop()
train_l = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
test_acc = evaluate_accuracy_gpu(net, test_iter)
print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
f'test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
f'on {str(device)}')
2.4训练命令行
lr, num_epochs = 0.9, 10
train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())