頭文件
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)絡
定義一個網(wǎng)絡類左驾,繼承原有nn.Module,內(nèi)部必須包含的2個函數(shù)
1.init():定義網(wǎng)絡的基本結(jié)構(gòu)极谊,需要
- 輸入層,即Flatten()
2.Sequential()層帆吻,用于定義串聯(lián)網(wǎng)絡層
2.forward(): 用于網(wǎng)絡前向計算,且與反向傳播無關(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)絡存入GPU
model = NeuralNetwork().to(device)
print(model)
網(wǎng)絡前向計算
使用網(wǎng)絡(model)輸入28*28像素的圖片咙边,獲得對應的預測概率,將概率輸入softmax王带,獲取最終預測結(jié)果市殷。
這里使用了nn.Softmax()實例,計算
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)絡層
nn.Flatten()
扁平化輸入搞挣,將2D圖像28*28直接串接為784維向量
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
nn.Linear()
使用給定的權(quán)重和bias進行全鏈層的線性計算甥桂,及y=Ax 的純線性映射
layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())
nn.ReLU()
非線性化計算,用于對線性計算結(jié)果的抗飽和調(diào)整黄选;
常見非線性話層有 sigmod, atanh貌夕, relu民镜,等抗飽和方法
如果沒有非線性化,理論上多個線性層疊加等價于一層们童,即y=Ax, y=BCDx, 此處 A=BCD,是完全等價
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
nn.Sequential()
組織各網(wǎng)絡計算層慧库,將其相互串聯(lián),依次計算(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ú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")