<jupyter_start><jupyter_text>建立神经网络[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_source.png)](https://gitee.com/mindspore/docs/blob/master/tutorials/source_zh_cn/model.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_notebook.png)](https://obs.dualstack.cn-north-4.myhuaweicloud.com/mindspore-website/notebook/master/tutorials/zh_cn/mindspore_model.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_modelarts.png)](https://authoring-modelarts-cnnorth4.huaweicloud.com/console/lab?share-url-b64=aHR0cHM6Ly9vYnMuZHVhbHN0YWNrLmNuLW5vcnRoLTQubXlodWF3ZWljbG91ZC5jb20vbWluZHNwb3JlLXdlYnNpdGUvbm90ZWJvb2svbW9kZWxhcnRzL3F1aWNrX3N0YXJ0L21pbmRzcG9yZV9tb2RlbC5pcHluYg==&imageid=65f636a0-56cf-49df-b941-7d2a07ba8c8c)神经网络模型由多个数据操作层组成，`mindspore.nn`提供了各种网络基础模块。在以下内容中，我们将以构建LeNet网络为例，展示MindSpore是如何建立神经网络模型的。首先导入本文档需要的模块和接口，如下所示：<jupyter_code>import numpy as np
import mindspore
import mindspore.nn as nn
from mindspore import Tensor<jupyter_output><empty_output><jupyter_text>定义模型类MindSpore的`Cell`类是构建所有网络的基类，也是网络的基本单元。当用户需要神经网络时，需要继承`Cell`类，并重写`__init__`方法和`construct`方法。<jupyter_code>class LeNet5(nn.Cell):
    """
    Lenet网络结构
    """
    def __init__(self, num_class=10, num_channel=1):
        super(LeNet5, self).__init__()
        # 定义所需要的运算
        self.conv1 = nn.Conv2d(num_channel, 6, 5, pad_mode='valid')
        self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
        self.fc1 = nn.Dense(16 * 5 * 5, 120)
        self.fc2 = nn.Dense(120, 84)
        self.fc3 = nn.Dense(84, num_class)
        self.relu = nn.ReLU()
        self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
        self.flatten = nn.Flatten()

    def construct(self, x):
        # 使用定义好的运算构建前向网络
        x = self.conv1(x)
        x = self.relu(x)
        x = self.max_pool2d(x)
        x = self.conv2(x)
        x = self.relu(x)
        x = self.max_pool2d(x)
        x = self.flatten(x)
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        x = self.relu(x)
        x = self.fc3(x)
        return x<jupyter_output><empty_output><jupyter_text>模型层本小节内容首先将会介绍LeNet网络中使用到`Cell`类的关键成员函数，然后通过实例化网络介绍如何利用`Cell`类访问模型参数。 nn.Conv2d加入`nn.Conv2d`层，给网络中加入卷积函数，帮助神经网络提取特征。<jupyter_code>conv2d = nn.Conv2d(1, 6, 5, has_bias=False, weight_init='normal', pad_mode='valid')
input_x = Tensor(np.ones([1, 1, 32, 32]), mindspore.float32)

print(conv2d(input_x).shape)<jupyter_output>(1, 6, 28, 28)<jupyter_text>nn.ReLU加入`nn.ReLU`层，给网络中加入非线性的激活函数，帮助神经网络学习各种复杂的特征。<jupyter_code>relu = nn.ReLU()
input_x = Tensor(np.array([-1, 2, -3, 2, -1]), mindspore.float16)
output = relu(input_x)

print(output)<jupyter_output>[0. 2. 0. 2. 0.]<jupyter_text>nn.MaxPool2d初始化`nn.MaxPool2d`层，将6×28×28的数组降采样为6×14×14的数组。<jupyter_code>max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
input_x = Tensor(np.ones([1, 6, 28, 28]), mindspore.float32)

print(max_pool2d(input_x).shape)<jupyter_output>(1, 6, 14, 14)<jupyter_text>nn.Flatten初始化`nn.Flatten`层，将16×5×5的数组转换为400个连续数组。<jupyter_code>flatten = nn.Flatten()
input_x = Tensor(np.ones([1, 16, 5, 5]), mindspore.float32)
output = flatten(input_x)

print(output.shape)<jupyter_output>(1, 400)<jupyter_text>nn.Dense初始化`nn.Dense`层，对输入矩阵进行线性变换。<jupyter_code>dense = nn.Dense(400, 120, weight_init='normal')
input_x = Tensor(np.ones([1, 400]), mindspore.float32)
output = dense(input_x)

print(output.shape)<jupyter_output>(1, 120)<jupyter_text>模型参数网络内部的卷积层和全连接层等实例化后，即具有权重和偏置，这些权重和偏置参数会在之后训练中进行优化。`nn.Cell`中使用`parameters_and_names()`方法访问所有参数。在示例中，我们遍历每个参数，并打印网络各层名字和属性。<jupyter_code>model = LeNet5()
for m in model.parameters_and_names():
    print(m)<jupyter_output>('conv1.weight', Parameter (name=conv1.weight, shape=(6, 1, 5, 5), dtype=Float32, requires_grad=True))
('conv2.weight', Parameter (name=conv2.weight, shape=(16, 6, 5, 5), dtype=Float32, requires_grad=True))
('fc1.weight', Parameter (name=fc1.weight, shape=(120, 400), dtype=Float32, requires_grad=True))
('fc1.bias', Parameter (name=fc1.bias, shape=(120,), dtype=Float32, requires_grad=True))
('fc2.weight', Parameter (name=fc2.weight, shape=(84, 120), dtype=Float32, requires_grad=True))
('fc2.bias', Parameter (name=fc2.bias, shape=(84,), dtype=Float32, requires_grad=True))
('fc3.weight', Parameter (name=fc3.weight, shape=(10, 84), dtype=Float32, requires_grad=True))
('fc3.bias', Parameter (name=fc3.bias, shape=(10,), dtype=Float32, requires_grad=True))
{'fraction_non_alphanumeric': 0.16090395480225989, 'fraction_numerical': 0.05785310734463277, 'mean_word_length': 6.003164556962025, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 6, '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': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '286158', 'license': 'Apache-2.0', 'n_tokens_mistral': 2295, 'n_tokens_neox': 2252, 'n_words': 209, 'path': 'tutorials/source_zh_cn/model.ipynb', 'repo_name': 'bwcsswcx/docs', 'size': '4425'}