网络构建
神经网络模型是由大量神经元(或节点)组成的模型,按照层次结构排列。一个神经网络莫i选哪个表示为一个Cell
,它由不同的子Cell
构成。
神经网络的基本步骤:
- 选择神经网络类型
- MLP
- CNN
- RNN
- Transformer
- GNN
- GAN
- 定义模型类
- 输入层
- 隐藏层
- 输出层
- 前向传播
- 数据输入
- 线性变换
- 将权重与输入点乘(加权和),并与偏置项相加
- 激活函数
- 加权和通过一个激活函数进行非线性转换。
- 生成输出
- 可根据具体任务(分类、回归)使用特定的激活函数。
- 反向传播
- 损失计算:
- 使用损失函数(均方误差、交叉熵等)计算输出值与真实值的差异
- 梯度计算:
- 反向传播核心是链式法则,用于计算损失函数相对于每个权重的偏导数(梯度)。从输出层开始,通过链式法则逐层向后计算每个权重对损失的影响。
- 权重更新:
- 计算出梯度后,使用优化算法(SGD、Adam等)更新网络中的权重,更新的主要目的是最小化损失。
- 反复迭代:
- 这个过程再多个训练周期(epochs)中重复进行,每次处理一批数据(batch)
- 直到模型性能达到指定的效果或达到设定的训练次数。
- 损失计算:
- 性能评估
- 分类:
- 准确率(Accuracy)
- 精确率(Precision)
- 召回率(Recall)
- F1分数(F1 Score)
- ROC曲线、AUC分数
- 混淆矩阵(Confusion Matrix)
- 回归:
- 均方误差(MSE)
- 均方根误差(RMSE)
- 平均绝对误差(MAE)
- 决定系数( R 2 R^2 R2)
- 平均绝对百分比误差(MAPE)
- 分类:
- 模型优化
- 超参数调整:
- 根据结果调整学习率、epochs或batch
- 正则化:
- L1正则化
- L2正则化
- Dropout()
- 超参数调整:
定义模型类
在定义神经网络时,可以继承nn.Cell
类,在__init__
方法中进行子Cell的实例化和状态管理,在construct
方法中实现Tensor操作。
construct
意为神经网络(计算图)构建,相关内容详见使用静态图加速。
from mindspore import nn
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
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输出,其包含每个类别的原始预测值。
model.construct()
方法不可直接调用。
import mindspore
from mindspore import ops
X = ops.ones((1, 28, 28), mindspore.float32)
logits = model(X)
pred_probab = nn.Softmax(axis=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")
输出:
Predicted class: [4]
模型层
本节中我们分解上节构造的神经网络模型中的每一层。首先我们构造一个shape为(3, 28, 28)的随机数据(3个28x28的图像),依次通过每一个神经网络层来观察其效果。
input_image = ops.ones((3, 28, 28), mindspore.float32)
print(input_image.shape)
输出:
(3, 28, 28)
nn.Flatten
实例化nn.Flatten层,将28x28的2D张量转换为784大小的连续数组。
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.shape)
输出:
(3, 784)
nn.Dense
nn.Dense为全连接层,其使用权重和偏差对输入进行线性变换。
layer1 = nn.Dense(in_channels=28*28, out_channels=20)
hidden1 = layer1(flat_image)
print(hidden1.shape)
输出:
(3, 20)
nn.ReLU
nn.ReLU层给网络中加入非线性的激活函数,帮助神经网络学习各种复杂的特征。
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
输出:
Before ReLU: [[-1.277866 0.666758 0.32021165 -0.19318968 -0.46870145 0.4733961
-0.87220997 -0.20886338 -0.69225127 -0.12731689 0.46299893 -0.07854332
0.6681083 0.6110305 -0.09762573 -0.4072349 -0.12635157 -0.18665327
-0.24946402 -0.21627676]
[-1.277866 0.666758 0.32021165 -0.19318968 -0.46870145 0.4733961
-0.87220997 -0.20886338 -0.69225127 -0.12731689 0.46299893 -0.07854332
0.6681083 0.6110305 -0.09762573 -0.4072349 -0.12635157 -0.18665327
-0.24946402 -0.21627676]
[-1.277866 0.666758 0.32021165 -0.19318968 -0.46870145 0.4733961
-0.87220997 -0.20886338 -0.69225127 -0.12731689 0.46299893 -0.07854332
0.6681083 0.6110305 -0.09762573 -0.4072349 -0.12635157 -0.18665327
-0.24946402 -0.21627676]]
After ReLU: [[0. 0.666758 0.32021165 0. 0. 0.4733961
0. 0. 0. 0. 0.46299893 0.
0.6681083 0.6110305 0. 0. 0. 0.
0. 0. ]
[0. 0.666758 0.32021165 0. 0. 0.4733961
0. 0. 0. 0. 0.46299893 0.
0.6681083 0.6110305 0. 0. 0. 0.
0. 0. ]
[0. 0.666758 0.32021165 0. 0. 0.4733961
0. 0. 0. 0. 0.46299893 0.
0.6681083 0.6110305 0. 0. 0. 0.
0. 0. ]]
nn.SequentialCell
nn.SequentialCell是一个有序的Cell容器。输入Tensor将按照定义的顺序通过所有Cell。我们可以使用SequentialCell
来快速组合构造一个神经网络模型。
seq_modules = nn.SequentialCell(
flatten,
layer1,
nn.ReLU(),
nn.Dense(20, 10)
)
logits = seq_modules(input_image)
print(logits.shape)
输出:
(3, 10)
nn.Softmax
最后使用nn.Softmax将神经网络最后一个全连接层返回的logits的值缩放为[0, 1],表示每个类别的预测概率。axis
指定的维度数值和为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")
输出:
Model structure: 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>
>
>
Layer: dense_relu_sequential.0.weight
Size: (512, 784)
Values : [[-0.01454661 -0.00052622 0.0134638 ... -0.00126561 0.00801466
-0.00590414]
[ 0.00028438 0.0286495 0.01709852 ... -0.00651062 -0.00503245
0.00225337]]
Layer: dense_relu_sequential.0.bias
Size: (512,)
Values : [0. 0.]
Layer: dense_relu_sequential.2.weight
Size: (512, 512)
Values : [[-0.00418757 -0.00146841 -0.00025317 ... 0.01138673 -0.00500975
-0.00834621]
[ 0.00015765 -0.00764043 -0.00253232 ... -0.00662186 -0.00926944
0.0051317 ]]
Layer: dense_relu_sequential.2.bias
Size: (512,)
Values : [0. 0.]
Layer: dense_relu_sequential.4.weight
Size: (10, 512)
Values : [[-5.30655868e-03 -1.40058983e-03 -8.17952459e-05 ... 6.50949718e-04
-1.01737154e-03 1.09181227e-02]
[-7.51176849e-03 -1.51963625e-02 1.02381669e-02 ... 7.55769433e-03
2.01417841e-02 -6.92950515e-03]]
Layer: dense_relu_sequential.4.bias
Size: (10,)
Values : [0. 0.]