《动手学深度学习 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)
)
相关推荐
hjs_deeplearning10 分钟前
认知篇#10:何为分布式与多智能体?二者联系?
人工智能·分布式·深度学习·学习·agent·智能体
瑶光守护者13 分钟前
【卫星通信】超低比特率语音编解码器(ULBC)的信道特性评估
深度学习·华为·卫星通信·3gpp·ulbc
kngines33 分钟前
【字节跳动】数据挖掘面试题0001:打车场景下POI与ODR空间关联查询
人工智能·数据挖掘·面试题
.30-06Springfield3 小时前
利用人名语言分类案例演示RNN、LSTM和GRU的区别(基于PyTorch)
人工智能·pytorch·python·rnn·分类·gru·lstm
xingshanchang5 小时前
PyTorch 不支持旧GPU的异常状态与解决方案:CUDNN_STATUS_NOT_SUPPORTED_ARCH_MISMATCH
人工智能·pytorch·python
reddingtons6 小时前
Adobe Firefly AI驱动设计:实用技巧与创新思维路径
大数据·人工智能·adobe·illustrator·photoshop·premiere·indesign
CertiK6 小时前
IBW 2025: CertiK首席商务官出席,探讨AI与Web3融合带来的安全挑战
人工智能·安全·web3
Deepoch6 小时前
Deepoc 大模型在无人机行业应用效果的方法
人工智能·科技·ai·语言模型·无人机
Deepoch7 小时前
Deepoc 大模型:无人机行业的智能变革引擎
人工智能·科技·算法·ai·动态规划·无人机
kngines7 小时前
【字节跳动】数据挖掘面试题0003:有一个文件,每一行是一个数字,如何用 MapReduce 进行排序和求每个用户每个页面停留时间
人工智能·数据挖掘·mapreduce·面试题