头文件
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")
自定义网络
定义一个网络类,继承原有nn.Module,内部必须包含的2个函数
1.init():定义网络的基本结构,需要
- 输入层,即Flatten()
2.Sequential()层,用于定义串联网络层
2.forward(): 用于网络前向计算,且与反向传播无关
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
网络存入GPU
model = NeuralNetwork().to(device)
print(model)
网络前向计算
使用网络(model)输入28*28像素的图片,获得对应的预测概率,将概率输入softmax,获取最终预测结果。
这里使用了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}")
典型网络层
nn.Flatten()
扁平化输入,将2D图像28*28直接串接为784维向量
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
nn.Linear()
使用给定的权重和bias进行全链层的线性计算,及y=Ax 的纯线性映射
layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())
nn.ReLU()
非线性化计算,用于对线性计算结果的抗饱和调整;
常见非线性话层有 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()
组织各网络计算层,将其相互串联,依次计算(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()
最终输出层,使用逻辑函数将[-inf, inf]映射到 [0, 1]并选出最大值,作为最终预测
入参 dim: 和为1的方向
dim parameter indicates the dimension along which the values must sum to 1.
softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
保存模型
模型参数可以在 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")