当前位置: 首页> 科技> IT业 > 昇思25天学习打卡营第6天|网络构建

昇思25天学习打卡营第6天|网络构建

时间:2025/7/12 6:50:34来源:https://blog.csdn.net/leifchen90/article/details/140104528 浏览次数:0次

网络构建

  • 概念
  • 模型
  • 模型参数

概念

神经网络模型是由神经网络层和Tensor操作构成的,mindspore.nn提供了常见神经网络层的实现,在MindSpore中,Cell类是构建所有网络的基类,也是网络的基本单元。一个神经网络模型表示为一个Cell,它由不同的子Cell构成。使用这样的嵌套结构,可以简单地使用面向对象编程的思维,对神经网络结构进行构建和管理。

模型

通过继承nn.Cell类,在__init__方法中进行子Cell的实例化和状态管理,在construct方法中实现Tensor操作。
代码示例:

import mindspore
from mindspore import nn, ops# 定义Network对象
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# 实例化Network对象,并查看其结构
model = Network()
print(model)
# 运行结果:
'''
Network<(flatten): Flatten<>(dense_relu_sequential): SequentialCell<(0): Dense<input_channels=784, output_channels=512, has_bias=True>(1): ReLU<>(2): Dense<input_channels=512, output_channels=512, has_bias=True>(3): ReLU<>(4): Dense<input_channels=512, output_channels=10, has_bias=True>>>
'''# 构造一个输入数据,直接调用模型,可以获得一个二维的Tensor输出,其包含每个类别的原始预测值
X = ops.ones((1, 28, 28), mindspore.float32)
logits = model(X)
# print logits
logits
# 运行结果(每次运行会有差异):
'''
Tensor(shape=[1, 10], dtype=Float32, value=
[[-4.65525780e-04,  6.57478347e-03, -6.96604839e-04 ... -3.72665562e-03,  4.10947762e-03,  1.58382324e-03]])
'''# 通过一个nn.Softmax层实例来获得预测概率
pred_probab = nn.Softmax(axis=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")
# 运行结果(每次运行会有差异):
# Predicted class: [1]

相关神经网络模型的API介绍:

  • nn.Flatten:沿着从 start_dim 到 end_dim 的维度,对输入Tensor进行展平。
  • nn.SequentialCell:构造Cell顺序容器。
  • nn.Dense:全连接层。
  • nn.ReLU:非线性激活函数层。逐元素计算ReLU(Rectified Linear Unit activation function)修正线性单元激活函数。
  • nn.Softmax:非线性激活函数层。逐元素计算Softmax激活函数,它是二分类函数 mindspore.nn.Sigmoid 在多分类上的推广,目的是将多分类的结果以概率的形式展现出来。

模型参数

网络内部神经网络层具有权重参数和偏置参数(如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")

截图时间
截图时间

关键字:昇思25天学习打卡营第6天|网络构建

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: