卷积神经网络(LeNet)

我运行代码的时候遇到了这个问题,请你最后解决这个问题了吗

为什么图片输入时是1维,而第一个卷积层却要使用6个通道?我很好奇这6个通道的值是如何获取到的?

Why does the first convolution layer use 6 channels when the image input is 1 dimension? I am curious how the values of these 6 channels are obtained?

lr, weight_decay, num_epochs = 0.1, 0, 80
net = nn.Sequential(
nn.Conv2d(1, 8, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(8, 8, kernel_size=3, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(8, 16, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(16, 16, kernel_size=3, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Linear(16 * 7 * 7, 256), nn.ReLU(), nn.Dropout(p=0.6),
nn.Linear(256, 128), nn.ReLU(), nn.Dropout(p=0.6),

loss 0.166, train acc 0.939, test acc 0.921
这时我得到的最高的测试正确率。dropout比weight_decay好用太多了在这个例子里面。

2 Likes

你也可以在加载train_iter和test_iter后加入如下两行代码:
train_iter.num_workers=0
test_iter.num_workers=0

1 Like

我修改了两个卷积层的核大小,test达到100%了是什么情况

    pooling_Layer = nn.AvgPool2d(kernel_size=2, stride=2)
    # pooling_Layer = nn.MaxPool2d(kernel_size=2, stride=2)
    activation_Layer = nn.Sigmoid()
    # activation_Layer = nn.ReLU()
    net = nn.Sequential(
        nn.Conv2d(1, 6, kernel_size=6, padding=2),
        activation_Layer,
        pooling_Layer,

        nn.Conv2d(6, 16, kernel_size=4),
        activation_Layer,
        pooling_Layer,

        nn.Flatten(),  # 图像平铺,准备进行MLP

        nn.Linear(16 * 5 * 5, 120),
        activation_Layer,

        nn.Linear(120, 84),
        activation_Layer,

        nn.Linear(84, 10)
    )
    X = torch.rand((1, 1, 28, 28), dtype=torch.float32)
    for layer in net:
        X = layer(X)
        print(layer.__class__.__name__, 'output shape:\t', X.shape)
    print('=' * 10)

    batch_size = 256
    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
    lr, num_epochs = 0.8, 16
    train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())

image

想问一下出现这个问题无法画图该如何解决呢?
I was running the code and found this error occured, and the graph is not sketched, how can I solve this problem?

你输出一下每一层的shape,调节或者增加卷积层的时候要注意和上一层的形状能对的上。

1 Like

maybe don’t try part above this train

我一开始也是这样,试试重启内核看看,或者重新运行所有代码,我的不知道为什么就好了

1.调整为maxpooling后:
loss 0.431, train acc 0.841, test acc 0.796
image
2.卷积核全部改成33,前面两层代替55,激活全部改成Relu,每两层卷积后面接一个最大池化,最后flatten,三个全连接改为240,120,10,训练epoch改成50,lr改成0.01,训练优化器改成adam,网络如下
image
训练结果如下:


感觉有点过拟合了,但是测试精度也比原来增加了10个点

增加weight_decay=0.005,epoch=25,拟合出一个还可以的模型
image

你代码敲错了,device在括号外面,应该是

device = next(iter(net.parameters())).device

1 Like

我觉得应该是lr设置太大了,改为0.1试一下

我个人建议用linux,然后别用Conda,少了很多麻烦。

你好,请问怎么调整train_ch6函数改用adam优化器呀

你好,请问怎么调整train_ch6函数改用adam优化器呢

在训练循环中,损失通常是计算为一批样本的平均损失。这样做的目的是使损失的量级独立于批次的大小,这样可以更容易地比较不同批次之间的损失,也有助于稳定训练过程。

在给定代码段中,l 是一批样本的平均损失,所以要计算整个批次的总损失,你需要将其乘以批次中的样本数量 X.shape[0]。随后,在累计损失和精度之后,你可以通过将这些值除以总样本数(metric[2])来计算整个训练集的平均损失和精度。

总结一下,将损失乘以批次大小并累计,然后再除以总样本数,等效于计算整个训练集的平均损失。这个方法可以使你更容易地跟踪训练过程中的损失,并且与批次大小无关。

第四题不太明白,请问第一层是6通道输出的话,那一个样本不是应该有6个feature map,9个样本不就应该有 9*6个feature map吗?

第四题
训练后模型:
经过第一个sigmoid后

感觉训练后的模型feature map 更能抓住特征了

#@save
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)}’)
请问训练函数里metric = d2l.Accumulator(3)没有移到GPU里,metric.add(l * X.shape【0】, d2l.accuracy(y_hat, y), X.shape【0】)为什么不会报错呢?