14、保存与加载PyTorch训练的模型和超参数
文章目录
- 1. state_dict
- 2. 模型保存
- 3. check_point
- 4. 详细保存
- 5. Docker
- 6. 机器学习常用库
1. state_dict
nn.Module 类是所有神经网络构建的基类,即自己构建一个深度神经网络也是需要继承自nn.Module类才行,并且nn.Module中的state_dict包含神经网络中的权重weight ,偏置bias,过程量buffer,举例说明:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :NN_Embedding.py
# @Time :2024/11/26 22:50
# @Author :Jason Zhang
import torch
from torch import nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.linear1 = nn.Linear(3, 4)
self.relu = nn.ReLU()
self.linear2 = nn.Linear(4, 5)
self.batch_norm = nn.BatchNorm2d(4)
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
y = self.linear2(x)
return y
if __name__ == "__main__":
my_test = MyModel()
my_keys = my_test.state_dict().keys()
print(f"my_keys={my_keys}")
- 结果:
从结果中看出,跟说明的一样,不仅存的是weight,bias ,还有buffer
y_keys=odict_keys(['linear1.weight', 'linear1.bias', 'linear2.weight', 'linear2.bias', 'batch_norm.weight', 'batch_norm.bias', 'batch_norm.running_mean', 'batch_norm.running_var', 'batch_norm.num_batches_tracked'])
2. 模型保存
保存和加载
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :torch_save.py
# @Time :2024/11/27 21:33
# @Author :Jason Zhang
import torch
import torchvision.models as models
if __name__ == "__main__":
run_code = 0
model = models.vgg16(weights='IMAGENET1K_V1')
torch.save(model.state_dict(), 'model_weights.pth')
model.load_state_dict(torch.load('model_weights.pth', weights_only=True))
model.eval()
torch.save(model, 'model.pth')
3. check_point
# Define model
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
class TheModelClass(nn.Module):
def __init__(self):
super(TheModelClass, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Initialize model
model = TheModelClass()
# Initialize optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# Print model's state_dict
print("Model's state_dict:")
for param_tensor in model.state_dict():
print(param_tensor, "\t", model.state_dict()[param_tensor].size())
# Print optimizer's state_dict
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
print(var_name, "\t", optimizer.state_dict()[var_name])
Model's state_dict:
conv1.weight torch.Size([6, 3, 5, 5])
conv1.bias torch.Size([6])
conv2.weight torch.Size([16, 6, 5, 5])
conv2.bias torch.Size([16])
fc1.weight torch.Size([120, 400])
fc1.bias torch.Size([120])
fc2.weight torch.Size([84, 120])
fc2.bias torch.Size([84])
fc3.weight torch.Size([10, 84])
fc3.bias torch.Size([10])
Optimizer's state_dict:
state {}
param_groups [{'lr': 0.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'maximize': False, 'foreach': None, 'differentiable': False, 'params': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}]
4. 详细保存
在训练过程中,我们希望详细保存,以至于我们可以在中断训练中恢复训练。
保存模型
5. Docker
关于Docker方式搭建深度神经网络环境和配置