网络的基本构建
构建网络的主要基类为:
torch.nn :包含了构建网络的所有基本模块;
nn.Module:基础网络,用于被继承;
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")
构建网络
创建自定义网络
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
构建网络实例
model = NeuralNetwork().to(device)
print(model)
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}")
常用网络模型函数
使用minibatch输入,使用3 张图片每组,图片大小为28*28。
input_image = torch.rand(3,28,28)
print(input_image.size())
flatten()
把2D数据展开为28*28=784维向量
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
nn.Linear
线性网络,
in_features: 网络输入维度
out_features: 网络输出维度
layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())
nn.ReLU
非线性层, 激活函数
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
nn.Sequential
各层串联函数
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
softmax函数,给出最终输出
softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
模型参数打印
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")