《动手学深度学习 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)
)
相关推荐
杭州默安科技16 分钟前
大模型AI Agent的工作原理与安全挑战
人工智能·安全
bug404_16 分钟前
jetson orin nano super AI模型部署之路(三)stable diffusion部署
人工智能·stable diffusion
Qiming_v17 分钟前
如何使用stable diffusion 3获得最佳效果
人工智能·stable diffusion
liruiqiang0536 分钟前
循环神经网络 - 通用近似定理 & 图灵完备
人工智能·rnn·深度学习·神经网络·机器学习
Panesle1 小时前
广告推荐算法:COSMO算法与A9算法的对比
人工智能·算法·机器学习·推荐算法·广告推荐
hunteritself1 小时前
DeepSeek重磅升级,豆包深度思考,ChatGPT原生生图,谷歌Gemini 2.5 Pro!| AI Weekly 3.24-3.30
人工智能·深度学习·chatgpt·开源·语音识别·deepseek
不要不开心了1 小时前
Scala内容
开发语言·pytorch·flask·scala·dash
Panesle1 小时前
transformer架构与其它架构对比
人工智能·深度学习·transformer
dundunmm2 小时前
【论文阅读】Self-Correcting Clustering
论文阅读·深度学习·数据挖掘·聚类