自学内容网 自学内容网

《昇思25天学习打卡营第5天 | mindspore 网络构建 Cell 常见用法》

1. 背景:

使用 mindspore 学习神经网络,打卡第五天;

2. 训练的内容:

使用 mindspore 的 nn.Cell 构建常见的网络使用方法;

3. 常见的用法小节:

支持一系列常用的 nn 的操作

3.1 nn.Cell 网络构建:

nn.Cell 基类的构建

 构建一个用于Mnist数据集分类的神经网络模型
import mindspore
from mindspore import nn, ops

# 一个神经网络模型表示为一个Cell, 它由不同的子Cell构成。使用这样的嵌套结构,可以简单地使用面向对象编程的思维,对神经网络结构进行构建和管理
class Network(nn.Cell):
    def __init__(self):
        super().__init__()
        
        self.flatten = nn.Flatten()
        self.dense_relu_sequential = nn.SequentialCell(
            nn.Dense(28 * 28, 512, weight_init = "normal", bias_init = "zeros"),
            nn.ReLU(),
            nn.Dense(512, 512, weight_init="normal", bias_init="zero"),
            nn.ReLU(),
            nn.Dense(512, 10, weight_init="normal", bias_init="zeros"),
        )
        
    # model.construct()方法不可直接调用
    def construct(self, x):
        x = self.flatten(x)
        logits = self.dense_relu_sequential(x)
        return logits

3.2 常见 nn 的模块的使用

  • nn.Flatten() 将 2D Tensor 转换成连续数组
  • nn.Dense: 全连接层,其使用权重和偏差对输入进行线性变换
  • nn.ReLU层: 给网络中加入非线性的激活函数,帮助神经网络学习各种复杂的特征。
  • nn.Softmax: 神经网络最后一个全连接层返回的logits的值缩放为[0, 1],表示每个类别的预测概率
    nn.SequentialCell: 一个有序的Cell容器。输入Tensor将按照定义的顺序通过所有Cell。
# 分解介绍

# 输入参数
input_image = ops.ones((3, 28, 28), mindspore.float32)
print(input_image.shape)

# 将28x28的2D张量转换为784大小的连续数组
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.shape)

# nn.Dense为全连接层,其使用权重和偏差对输入进行线性变换
layer1 = nn.Dense(in_channels=28*28, out_channels=20)
hidden1 = layer1(flat_image)
print(hidden1.shape)

# nn.ReLU层给网络中加入非线性的激活函数,帮助神经网络学习各种复杂的特征。
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")

# nn.SequentialCell是一个有序的Cell容器。输入Tensor将按照定义的顺序通过所有Cell。我们可以使用nn.SequentialCell来快速组合构造一个神经网络模型。
seq_modules = nn.SequentialCell(
    flatten,
    layer1,
    nn.ReLU(),
    nn.Dense(20, 10)
)

logits = seq_modules(input_image)
print(logits.shape)

# 最后使用nn.Softmax将神经网络最后一个全连接层返回的logits的值缩放为[0, 1],表示每个类别的预测概率
softmax = nn.Softmax(axis=1)
pred_probab = softmax(logits)

# 模型参数
print(f"Model structure: {model}\n\n")

for name, param in model.parameters_and_names():
    print(f"Layer: {name}\nSize: {param.shape}\nValues : {param[:2]} \n")
    

活动参与链接:

https://xihe.mindspore.cn/events/mindspore-training-camp


原文地址:https://blog.csdn.net/comedate/article/details/140138232

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!