1個空間做兩個網(wǎng)站百度網(wǎng)盤app下載安裝官方免費版
?一、簡介:
神經(jīng)網(wǎng)絡模型是由神經(jīng)網(wǎng)絡層和Tensor操作構成的,mindspore.nn提供了常見神經(jīng)網(wǎng)絡層的實現(xiàn),在MindSpore中,Cell類是構建所有網(wǎng)絡的基類(這個類和pytorch中的modul類是一樣的作用),也是網(wǎng)絡的基本單元。一個神經(jīng)網(wǎng)絡模型表示為一個Cell
,它由不同的子Cell
構成。使用這樣的嵌套結構,可以簡單地使用面向?qū)ο缶幊痰乃季S,對神經(jīng)網(wǎng)絡結構進行構建和管理。
二、環(huán)境準備:
import mindspore
import time
from mindspore import nn, ops
沒有下載mindspore的寶子,還是回看我的昇思25天學習打卡營第1天|快速入門-CSDN博客,先下載好再進行下面的操作。
三、神經(jīng)網(wǎng)絡搭建:
1、定義模型類:
我們首先要繼承nn.Cell類,并再__init__方法中進行子Cell的實例化和管理,并再construct方法(和pytorch中的forward方法一致)中實現(xiàn)前向計算:
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)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())), "VertexGeek")
?①self.flatten = nn.Flatten()
:創(chuàng)建一個Flatten層,并將其作為類的屬性。Flatten層的作用是將輸入的數(shù)據(jù)“壓平”,即不管輸入數(shù)據(jù)的原始形狀如何,輸出都將是沿著特定維度的連續(xù)數(shù)組。
②?self.dense_relu_sequential = nn.SequentialCell(...)
:創(chuàng)建一個SequentialCell
,它是一種特殊的Cell,可以順序地執(zhí)行其中包含的多個層。這個SequentialCell
包含了三個全連接層(Dense
),每個全連接層后面跟著一個ReLU激活函數(shù)層,除了最后一個全連接層:
-
第一個
nn.Dense(28*28, 512, weight_init="normal", bias_init="zeros")
:這是一個全連接層,它接受28*28=784個輸入,并產(chǎn)生512個輸出。權重(weight_init
)和偏置(bias_init
)分別使用正態(tài)分布和零值進行初始化。 -
nn.ReLU()
:ReLU激活函數(shù),其數(shù)學表達式為f(x) = max(0, x)
,即負值輸出為零,正值保持不變。 -
接下來的兩個
nn.Dense
與對應的nn.ReLU
層與第一個類似,它們分別接收512個輸入并再次輸出512個值,以及最終輸出10個值,這可能對應于10個類別。
我們構造一個數(shù)據(jù),并使用softmax預測其概率:
X = ops.ones((1, 28, 28), mindspore.float32)
logits = model(X)
# print logits
print(logits)pred_probab = nn.Softmax(axis=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())), "VertexGeek")
2、模型層詳解:
(1)nn.Flatten:
?nn.Flantten方法用于將輸入數(shù)據(jù)“壓平”,以便后續(xù)處理:
input_image = ops.ones((3, 28, 28), mindspore.float32)
print(input_image.shape)flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.shape)print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())), "VertexGeek")
(2)nn.Dense:
?nn.Dense層作為全連接層,用于對輸入的數(shù)據(jù)進行線性變換和處理:
layer1 = nn.Dense(in_channels=28*28, out_channels=20)
hidden1 = layer1(flat_image)
print(hidden1.shape)print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())), "VertexGeek")
(3)nn.Relu:
nn.Relu是本次實驗中使用的激活函數(shù),用于對神經(jīng)網(wǎng)絡的權重進行處理,以緩解欠擬合和過擬合的發(fā)生,常見的激活函數(shù)處了Relu,還有:Sigmoid,?Tanh等:
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())), "VertexGeek")
?(4)nn.SequentialCell:
nn.SequentialCell和pytorch中的nn.Sequential的作用一樣,用于存放dense全連接層和激活函數(shù)層的組合,以方便在前向計算中使用:
seq_modules = nn.SequentialCell(flatten,layer1,nn.ReLU(),nn.Dense(20, 10)
)logits = seq_modules(input_image)
print(logits.shape)print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())), "VertexGeek")
(5)nn.Softmax:
?nn.softmax方法將神經(jīng)網(wǎng)絡最后一個全連接層返回的logits的值縮放為[0, 1],表示每個類別的預測概率。axis
指定的維度數(shù)值和為1。
softmax = nn.Softmax(axis=1)
pred_probab = softmax(logits)
print(pred_probab)
# argmax函數(shù)返回指定維度上最大值的索引
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())), "VertexGeek")
3、模型參數(shù):
網(wǎng)絡內(nèi)部神經(jīng)網(wǎng)絡層具有權重參數(shù)和偏置參數(shù)(如nn.Dense
),這些參數(shù)會在訓練過程中不斷進行優(yōu)化,可通過?model.parameters_and_names()
?來獲取參數(shù)名及對應的參數(shù)詳情。
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")print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())), "VertexGeek")
?