《动手学深度学习 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)
)
相关推荐
海盗儿33 分钟前
Attention Is All You Need (Transformer) 以及Transformer pytorch实现
pytorch·深度学习·transformer
GIS小天1 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票
阿部多瑞 ABU1 小时前
主流大语言模型安全性测试(三):阿拉伯语越狱提示词下的表现与分析
人工智能·安全·ai·语言模型·安全性测试
cnbestec1 小时前
Xela矩阵三轴触觉传感器的工作原理解析与应用场景
人工智能·线性代数·触觉传感器
不爱写代码的玉子1 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
sbc-study1 小时前
PCDF (Progressive Continuous Discrimination Filter)模块构建
人工智能·深度学习·计算机视觉
EasonZzzzzzz2 小时前
计算机视觉——相机标定
人工智能·数码相机·计算机视觉
猿小猴子2 小时前
主流 AI IDE 之一的 Cursor 介绍
ide·人工智能·cursor
要努力啊啊啊2 小时前
Reranker + BM25 + FAISS 构建高效的多阶段知识库检索系统一
人工智能·语言模型·自然语言处理·faiss
EasyDSS2 小时前
国标GB28181设备管理软件EasyGBS远程视频监控方案助力高效安全运营
网络·人工智能