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