创建一个网络
建立一个简单的三层的网络。
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor()
)
train_dataloader = DataLoader(training_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
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()
给出网络参数
learning_rate = 1e-3 #学习率,每次沿梯度方向前进步长
batch_size = 64 #每次跟新梯度的数据数
epochs = 5 #总训练迭代次数
损失函数
常见的顺势函数为:
nn.MSELoss : Mean Square Error
nn.NLLoss : Negative Log Likelihood
nn.CrossEntropyLoss: nnLogSoftmax + nn.NLLLoss
# Initialize the loss function
loss_fn = nn.CrossEntropyLoss()
优化器
optimizer表示网络使用何种方法(这里主要涉及梯度和学习率)更新网络参数的过程,常用的梯度更新方式有:
SGD: 随机梯度下降法(stochatic gradient decent)
ADAM: 考虑动量的梯度方法
RMSProp:
详情可参见官方说明: https://pytorch.org/docs/stable/optim.html
一篇非常好的介绍各种梯度方法的博客: https://ruder.io/optimizing-gradient-descent/index.html#adam
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
在每个优化循环中主要包含如下三步:
optimizer.zero_grad(): 清空梯度累计
loss.backward(): 方向传播,使用loss函数累计梯度(累积和batch有关系)
optimizer.step(): 使用累计的梯度,更新参数
完整的训练过程
定义一个train_loop()函数进行网络训练
定一个test_loop()函数反馈网络预测结果
相关函数定义如下:
def train_loop(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
for batch, (X, y) in enumerate(dataloader):
# Compute prediction and loss
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
loss, current = loss.item(), batch * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test_loop(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
一个完整的训练,优化过程:
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
epochs = 10
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train_loop(train_dataloader, model, loss_fn, optimizer)
test_loop(test_dataloader, model, loss_fn)
print("Done!")
训练结果的载入和保存
torch 在网络完成训练后,可以将网络参数以字典( .state_dict() )的形式保存为.pth文件。
import torch
import torchvision.models as models
model = models.vgg16(pretrained=True)
torch.save(model.state_dict(), 'model_weights.pth')
同样也可以讲一训练好的网络参数导入:
model = models.vgg16() # we do not specify pretrained=True, i.e. do not load default weights
model.load_state_dict(torch.load('model_weights.pth'))
model.eval()
保存网络模型结构
torch.save(model, 'model.pth')
载入网络模型结构
model = torch.load('model.pth')