<jupyter_start><jupyter_text>卷积神经网络（LeNet）LeNet（LeNet-5）由两个部分组成：卷积编码器和全连接层密集块<jupyter_code>import sys
sys.path.append('..')
import mindspore
import numpy as np
from mindspore import nn
from d2l import mindspore as d2l

net = nn.SequentialCell([
    nn.Conv2d(1, 6, kernel_size=5, padding=2, pad_mode='pad', weight_init='xavier_uniform'),
    nn.Sigmoid(),
    nn.AvgPool2d(kernel_size=2, stride=2),
    nn.Conv2d(6, 16, kernel_size=5, pad_mode='valid', weight_init='xavier_uniform'),
    nn.Sigmoid(),
    nn.AvgPool2d(kernel_size=2, stride=2),
    nn.Flatten(),
    nn.Dense(16 * 5 * 5, 120, weight_init='xavier_uniform'),
    nn.Sigmoid(),
    nn.Dense(120, 84, weight_init='xavier_uniform'),
    nn.Sigmoid(),
    nn.Dense(84, 10, weight_init='xavier_uniform')
])<jupyter_output><empty_output><jupyter_text>检查模型<jupyter_code>X = mindspore.Tensor(np.random.rand(1, 1, 28, 28), mindspore.float32)
for layer in net:
    X = layer(X)
    print(layer.__class__.__name__,'output shape: \t',X.shape)<jupyter_output>Conv2d output shape: 	 (1, 6, 28, 28)
Sigmoid output shape: 	 (1, 6, 28, 28)
AvgPool2d output shape: 	 (1, 6, 14, 14)
Conv2d output shape: 	 (1, 16, 10, 10)
Sigmoid output shape: 	 (1, 16, 10, 10)
AvgPool2d output shape: 	 (1, 16, 5, 5)
Flatten output shape: 	 (1, 400)
Dense output shape: 	 (1, 120)
Sigmoid output shape: 	 (1, 120)
Dense output shape: 	 (1, 84)
Sigmoid output shape: 	 (1, 84)
Dense output shape: 	 (1, 10)<jupyter_text>LeNet在Fashion-MNIST数据集上的表现<jupyter_code>batch_size = 256
mnist_train, mnist_test = d2l.load_data_fashion_mnist('../data', batch_size=batch_size)<jupyter_output><empty_output><jupyter_text>对`evaluate_accuracy`函数进行轻微的修改<jupyter_code>def evaluate_accuracy_gpu(net, dataset, device=None): 
    """使用GPU计算模型在数据集上的精度。"""
    net.set_train(False)
    metric = d2l.Accumulator(2)
    for X, y in dataset.create_tuple_iterator():
        metric.add(d2l.accuracy(net(X), y), y.size)
    return metric[0] / metric[1]
def train_ch6(net, train_dataset, test_dataset, num_epochs, lr):
    """用GPU训练模型(在第六章定义)。"""
    optim = nn.SGD(net.trainable_params(), learning_rate=lr)
    loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
    net_with_loss = nn.WithLossCell(net, loss)
    train = nn.TrainOneStepCell(net_with_loss, optim)
    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
                            legend=['train loss', 'train acc', 'test acc'])
    timer, num_batches = d2l.Timer(), train_dataset.get_dataset_size()
    for epoch in range(num_epochs):
        metric = d2l.Accumulator(3)
        net.set_train()
        for i, (X, y) in enumerate(train_dataset.create_tuple_iterator()):
            timer.start()
            l = train(X, y)
            y_hat = net(X)
            metric.add(l.asnumpy() * 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_dataset)
        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')<jupyter_output><empty_output><jupyter_text>训练和评估LeNet-5模型<jupyter_code>lr, num_epochs = 0.9, 10
train_ch6(net, mnist_train, mnist_test, num_epochs, lr)<jupyter_output>loss 0.470, train acc 0.837, test acc 0.819
52451.5 examples/sec
{'fraction_non_alphanumeric': 0.14543466375068342, 'fraction_numerical': 0.04428649535265172, 'mean_word_length': 3.7892670157068062, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '588041', 'license': 'MIT', 'n_tokens_mistral': 1588, 'n_tokens_neox': 1505, 'n_words': 279, 'path': 'chapter_06_convolutional-neural-networks/4_lenet.ipynb', 'repo_name': 'lvyufeng/d2l-mindspore', 'size': '3658'}