《动手学深度学习 Pytorch版》 5.5 读写文件

5.5.1 加载和保存

python 复制代码
import torch
from torch import nn
from torch.nn import functional as F

x = torch.arange(4)
torch.save(x, 'x-file')  # 使用 save 保存
python 复制代码
x2 = torch.load('x-file')  # 使用 load 读回内存
x2
复制代码
tensor([0, 1, 2, 3])
python 复制代码
y = torch.zeros(4)
torch.save([x, y],'x-files')  # 也可以存储张量列表
x2, y2 = torch.load('x-files')
(x2, y2)
复制代码
(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))
python 复制代码
mydict = {'x': x, 'y': y}  # 存储从字符串映射到张量的字典
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
mydict2
复制代码
{'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}

5.5.2 加载和保存模型参数

python 复制代码
class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(20, 256)
        self.output = nn.Linear(256, 10)

    def forward(self, x):
        return self.output(F.relu(self.hidden(x)))

net = MLP()
X = torch.randn(size=(2, 20))
Y = net(X)

torch.save(net.state_dict(), 'mlp.params')  # 保存模型参数
python 复制代码
clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))  # 加载文件中存储的参数

Y_clone = clone(X)  # 参数一致则计算结果也应相同

clone.eval(), Y_clone == Y
复制代码
(MLP(
   (hidden): Linear(in_features=20, out_features=256, bias=True)
   (output): Linear(in_features=256, out_features=10, bias=True)
 ),
 tensor([[True, True, True, True, True, True, True, True, True, True],
         [True, True, True, True, True, True, True, True, True, True]]))

练习

(1)即使不需要将经过训练的模型部署到不同的设备上,保存的模型参数还有什么实际的好处?

用作备份或备为下一步处理均可。


(2)假设我们只想复用网络的一部分,已将其合并到不同的网络架构中。例如想在一个新的网络中使用之前网络的前两层,该怎么做?

python 复制代码
torch.save(net.hidden.state_dict(), 'mlp.hidden.params')  # 需要哪里存哪里
clone = MLP()
clone.hidden.load_state_dict(torch.load('mlp.hidden.params'))  # 需要哪里加载哪里

clone.eval(), clone.hidden.weight == net.hidden.weight
复制代码
(MLP(
   (hidden): Linear(in_features=20, out_features=256, bias=True)
   (output): Linear(in_features=256, out_features=10, bias=True)
 ),
 tensor([[True, True, True,  ..., True, True, True],
         [True, True, True,  ..., True, True, True],
         [True, True, True,  ..., True, True, True],
         ...,
         [True, True, True,  ..., True, True, True],
         [True, True, True,  ..., True, True, True],
         [True, True, True,  ..., True, True, True]]))

(3)如何同时保存网络架构和参数?需要对架构加上什么限制?

python 复制代码
net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
torch.save(net, 'net')  # pytorch 本身就支持保存模型
net_new = torch.load('net')
net_new
复制代码
Sequential(
  (0): Linear(in_features=20, out_features=256, bias=True)
  (1): ReLU()
  (2): Linear(in_features=256, out_features=10, bias=True)
)
相关推荐
视觉语言导航30 分钟前
湖南大学3D场景问答最新综述!3D-SQA:3D场景问答助力具身智能场景理解
人工智能·深度学习·具身智能
AidLux30 分钟前
端侧智能重构智能监控新路径 | 2025 高通边缘智能创新应用大赛第三场公开课来袭!
大数据·人工智能
引量AI39 分钟前
TikTok矩阵运营干货:从0到1打造爆款矩阵
人工智能·矩阵·自动化·tiktok矩阵·海外社媒
Hi-Dison1 小时前
神经网络极简入门技术分享
人工智能·深度学习·神经网络
奋斗者1号1 小时前
机器学习之决策树模型:从基础概念到条件类型详解
人工智能·决策树·机器学习
LinkTime_Cloud1 小时前
谷歌引入 AI 反诈系统:利用语言模型分析潜在恶意网站
人工智能·语言模型·自然语言处理
张小九991 小时前
PyTorch的dataloader制作自定义数据集
人工智能·pytorch·python
Panesle1 小时前
分布式异步强化学习框架训练32B大模型:INTELLECT-2
人工智能·分布式·深度学习·算法·大模型
zstar-_2 小时前
FreeTex v0.2.0:功能升级/支持Mac
人工智能·python·macos·llm
于壮士hoho2 小时前
DeepSeek | AI需求分析
人工智能·python·ai·需求分析·dash