欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > 14、保存与加载PyTorch训练的模型和超参数

14、保存与加载PyTorch训练的模型和超参数

2024/12/26 19:51:01 来源:https://blog.csdn.net/scar2016/article/details/144094937  浏览:    关键词: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 nnclass 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 yif __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 modelsif __name__ == "__main__":run_code = 0model = 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 Fclass 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方式搭建深度神经网络环境和配置
在这里插入图片描述

6. 机器学习常用库

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com