卷积神经网络(LeNet)
最近在B站看沐神的动手学深度学习视频,记录一下学习过程 查看本文的jupyter notebook格式,更加清晰美观哦!
含但隐藏层的多层感知机模型对图像进行分了的方法有一定的局限性。1.图像在同一列邻近的像素在向量中可能相距较远。它们构成的模式可能难以被模型识别。2.对于大尺寸的图像,使用全连接层容易导致模型过大。卷积层尝试解决这两个问题:一方面,卷积层保留输入形状,使图像的像素在宽高两个方向上的相关性均可能被有效识别;另一方面,卷积层通过滑动窗口将同一卷积核与不同位置的输入重复计算,从而避免参数尺寸过大。
LeNet模型
LeNet分为卷积层块和全连接层块两个部分。卷积层块的基本单位是卷积层后接最大池化层:卷积层用来识别图像中的空间模式,如线条和物体局部,之后的最大池化层用来降低卷积层对位置的敏感性。卷积层块的输出形状为(批量大小,通道,高,宽)。当卷积层块的输出传入全连接层块时,全连接层块会将小批量中的每个样本变平(flatten)。也就是说,全连接层的形状变为二维,其中第一维是小批量中的样本,第二维是每个样本变平后的向量表示。
import time
import mxnet as mx
import d2lzh as d2l
from mxnet import nd, init, gluon, autograd
from mxnet.gluon import loss as gloss, nn
net = nn.Sequential()
net.add(nn.Conv2D(channels=6, kernel_size=5, activation='sigmoid'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Conv2D(channels=16, kernel_size=5, activation='sigmoid'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Dense(120, activation='sigmoid'),
nn.Dense(84, activation='sigmoid'),
nn.Dense(10))
构造一个高和宽均为28的单通道数据样本,并逐层进行前向计算查看每层的输出形状
X = nd.random.uniform(shape=(1, 1, 28, 28))
net.initialize()
for layer in net:
X = layer(X)
print(layer.name, 'output shape:\t', X.shape)
conv0 output shape: (1, 6, 24, 24)
pool0 output shape: (1, 6, 12, 12)
conv1 output shape: (1, 16, 8, 8)
pool1 output shape: (1, 16, 4, 4)
dense0 output shape: (1, 120)
dense1 output shape: (1, 84)
dense2 output shape: (1, 10)
获取数据和训练模型
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
卷积神经网络计算比多层感知机要复杂,建议使用GPU来加速计算。尝试在gpu(0)上创建NDArray,如果成功则使用gpu(0),否则仍然使用CPU。
def try_gpu():
try:
ctx = mx.gpu()
_ = nd.zeros((1,), ctx=ctx)
except mx.base.MXNetError:
ctx = mx.cpu()
return ctx
ctx = try_gpu()
ctx
cpu(0)
对“softmax回归的从零开始实现”一节中描述的evaluate_accuracy函数略作修改.当ctx变量代表GPU及相应的显存时,通过as_in_context函数将数据复制到显存上,例如gpu(0)。
def evaluate_accuracy(data_iter, net, ctx):
acc_sum, n = nd.array([0], ctx=ctx), 0
for X, y in data_iter:
X, y = X.as_in_context(ctx), y.as_in_context(ctx).astype('float32')
acc_sum += (net(X).argmax(axis=1) == y).sum()
n += y.size
return acc_sum.asscalar() / n
对train_ch3函数略作修改
def train_ch5(net, train_iter, test_iter, batch_size, trainer, ctx, num_epochs):
print('training on', ctx)
loss = gloss.SoftmaxCrossEntropyLoss()
for epoch in range(num_epochs):
train_l_sum, train_acc_sum, n, start = 0.0, 0.0, 0, time.time()
for X, y in train_iter:
X, y = X.as_in_context(ctx), y.as_in_context(ctx)
with autograd.record():
y_hat = net(X)
l = loss(y_hat, y).sum()
l.backward()
trainer.step(batch_size)
y = y.astype('float32')
train_l_sum += l.asscalar()
train_acc_sum += (y_hat.argmax(axis=1) == y).sum().asscalar()
n += y.size
test_acc = evaluate_accuracy(test_iter, net, ctx)
print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f, time %.1f sec' %
(epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc, time.time() - start))
lr, num_epochs = 0.9, 5
net.initialize(force_reinit=True, ctx=ctx, init=init.Xavier())
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': lr})
train_ch5(net, train_iter, test_iter, batch_size, trainer, ctx, num_epochs)
training on cpu(0)
epoch 1, loss 2.3193, train acc 0.103, test acc 0.100, time 35.3 sec
epoch 2, loss 1.6310, train acc 0.368, test acc 0.610, time 35.3 sec
epoch 3, loss 0.9264, train acc 0.636, test acc 0.713, time 37.7 sec
epoch 4, loss 0.7382, train acc 0.710, test acc 0.746, time 36.7 sec
epoch 5, loss 0.6659, train acc 0.736, test acc 0.763, time 36.5 sec
|