《动手学深度学习 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)
)
相关推荐
z are8 分钟前
PyTorch 生态四件套:从图片、视频到文本、语音的“开箱即用”实践笔记
人工智能·pytorch·笔记·深度学习
Ly2020Wj9 分钟前
pytorch入门:利用pytorch进行线性预测
人工智能·pytorch·python
运维开发王义杰19 分钟前
AI: 告别过时信息, 用RAG和一份PDF 为LLM打造一个随需更新的“外脑”
人工智能
老鱼说AI21 分钟前
实例教学FPN原理与PANet,Pytorch逐行精讲实现
人工智能·深度学习
芷栀夏37 分钟前
如何通过IT-Tools与CPolar构建无缝开发通道?
网络·人工智能·python
CodeShare40 分钟前
谷歌推出基于Gemini 2.0的机器人AI模型
人工智能·多模态模型·机器人技术
偶尔贪玩的骑士43 分钟前
Note3: CNN(卷积神经网络)
人工智能·神经网络·cnn
饭碗、碗碗香1 小时前
【vLLM学习笔记】:vLLM 参数说明
人工智能·笔记·学习·ai
audyxiao0012 小时前
2025年6月数据挖掘顶刊TKDE研究热点有哪些?
人工智能·数据挖掘·大模型·热点分析·tkde
chxin140163 小时前
循环神经网络——动手学深度学习7
人工智能·pytorch·rnn·深度学习