頭文件
import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")
自定義網(wǎng)絡(luò)
定義一個(gè)網(wǎng)絡(luò)類(lèi),繼承原有nn.Module,內(nèi)部必須包含的2個(gè)函數(shù)
1.init():定義網(wǎng)絡(luò)的基本結(jié)構(gòu),需要
- 輸入層,即Flatten()
2.Sequential()層,用于定義串聯(lián)網(wǎng)絡(luò)層
2.forward(): 用于網(wǎng)絡(luò)前向計(jì)算,且與反向傳播無(wú)關(guān)
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
網(wǎng)絡(luò)存入GPU
model = NeuralNetwork().to(device)
print(model)
網(wǎng)絡(luò)前向計(jì)算
使用網(wǎng)絡(luò)(model)輸入28*28像素的圖片,獲得對(duì)應(yīng)的預(yù)測(cè)概率,將概率輸入softmax,獲取最終預(yù)測(cè)結(jié)果。
這里使用了nn.Softmax()實(shí)例,計(jì)算
X = torch.rand(1, 28, 28, device=device)
logits = model(X)
pred_probab = nn.Softmax(dim=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")
典型網(wǎng)絡(luò)層
nn.Flatten()
扁平化輸入,將2D圖像28*28直接串接為784維向量
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
nn.Linear()
使用給定的權(quán)重和bias進(jìn)行全鏈層的線(xiàn)性計(jì)算,及y=Ax 的純線(xiàn)性映射
layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())
nn.ReLU()
非線(xiàn)性化計(jì)算,用于對(duì)線(xiàn)性計(jì)算結(jié)果的抗飽和調(diào)整;
常見(jiàn)非線(xiàn)性話(huà)層有 sigmod, atanh, relu,等抗飽和方法
如果沒(méi)有非線(xiàn)性化,理論上多個(gè)線(xiàn)性層疊加等價(jià)于一層,即y=Ax, y=BCDx, 此處 A=BCD,是完全等價(jià)
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
nn.Sequential()
組織各網(wǎng)絡(luò)計(jì)算層,將其相互串聯(lián),依次計(jì)算(ordered container);
seq_modules = nn.Sequential(
flatten,
layer1,
nn.ReLU(),
nn.Linear(20, 10)
)
input_image = torch.rand(3,28,28)
logits = seq_modules(input_image)
nn.Softmax()
最終輸出層,使用邏輯函數(shù)將[-inf, inf]映射到 [0, 1]并選出最大值,作為最終預(yù)測(cè)
入?yún)?dim: 和為1的方向
dim parameter indicates the dimension along which the values must sum to 1.
softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
保存模型
模型參數(shù)可以在 model.named_parameters()中讀取
print(f"Model structure: {model}\n\n")
for name, param in model.named_parameters():
print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")