首页 > 其他分享 >【MindSpore学习打卡】初学教程-06网络构建-使用MindSpore构建神经网络模型

【MindSpore学习打卡】初学教程-06网络构建-使用MindSpore构建神经网络模型

时间:2024-06-23 15:59:42浏览次数:3  
标签:nn 模型 init 神经网络 构建 print 打卡 logits MindSpore

在深度学习的世界中,构建和训练神经网络模型是核心任务之一。MindSpore作为一款开源的深度学习框架,提供了丰富的API和工具,使得构建神经网络模型变得更加简洁和高效。在这篇博客中,我们将以Mnist数据集分类为例,逐步讲解如何使用MindSpore定义模型、构建网络层并进行预测。通过本文,你将全面了解MindSpore中神经网络的构建方法,并掌握一些实用技巧。

定义模型类

在MindSpore中,所有的神经网络模型都是通过继承nn.Cell类来定义的。在__init__方法中进行子Cell的实例化和状态管理,在construct方法中实现Tensor操作。这种设计使得模型的定义更加模块化和易于管理:

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="zeros"),
            nn.ReLU(),
            nn.Dense(512, 10, weight_init="normal", bias_init="zeros")
        )

    def construct(self, x):
        x = self.flatten(x)
        logits = self.dense_relu_sequential(x)
        return logits

通过继承nn.Cell类,我们可以利用面向对象编程的思想来构建和管理神经网络模型,这使得代码更具可读性和可维护性。

实例化模型

构建完成后,实例化Network对象,并查看其结构,这样做的目的是确保模型定义正确,并了解模型的整体结构,以便后续调试和优化。

model = Network()
print(model)

我们构造一个输入数据,直接调用模型,可以获得一个十维的Tensor输出,其包含每个类别的原始预测值。

X = ops.ones((1, 28, 28), mindspore.float32)
logits = model(X)
logits

在此基础上,我们通过一个nn.Softmax层实例来获得预测概率:

pred_probab = nn.Softmax(axis=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")

模型层解析

接下来,我们将分解上面构造的神经网络模型中的每一层,并观察其效果。通过这种方式,我们可以逐步验证每一层的行为,确保模型的正确性。

nn.Flatten

实例化nn.Flatten层,将28x28的2D张量转换为784大小的连续数组:

input_image = ops.ones((3, 28, 28), mindspore.float32)
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.shape)

nn.Dense

nn.Dense为全连接层,其使用权重和偏差对输入进行线性变换:

layer1 = nn.Dense(in_channels=28*28, out_channels=20)
hidden1 = layer1(flat_image)
print(hidden1.shape)

nn.ReLU

nn.ReLU层给网络中加入非线性的激活函数,帮助神经网络学习各种复杂的特征:

print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")

nn.SequentialCell

nn.SequentialCell是一个有序的Cell容器,输入Tensor将按照定义的顺序通过所有Cell:

seq_modules = nn.SequentialCell(
    flatten,
    layer1,
    nn.ReLU(),
    nn.Dense(20, 10)
)

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

nn.Softmax

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

softmax = nn.Softmax(axis=1)
pred_probab = softmax(logits)

模型参数

网络内部神经网络层具有权重参数和偏置参数(如nn.Dense),这些参数会在训练过程中不断进行优化。可通过 model.parameters_and_names() 来获取参数名及对应的参数详情:

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")

总结

通过本文的详细讲解,我们从零开始构建了一个用于Mnist数据集分类的神经网络模型,并深入解析了模型中的每一层。希望这篇博客能帮助你更好地理解和使用MindSpore进行神经网络的构建和训练。
在这里插入图片描述

标签:nn,模型,init,神经网络,构建,print,打卡,logits,MindSpore
From: https://blog.csdn.net/weixin_43427267/article/details/139901459

相关文章