5-5读写文件

1.加载和保存张量

import torch
from torch import nn
from torch.nn import functional as F

x = torch.arange(4)
# 把 Python 对象 x 打包成字节流,原封不动地写进文件 x-file,
# 以后可以用 torch.load('x-file') 原样还原
torch.save(x, 'x-file')
# 加载数据并输出
x2 = torch.load('x-file')
print(x2)
tensor([0, 1, 2, 3])
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.]))
# 写入或读取从字符串映射道张量的字典
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.])}

2.加载和保存模型参数

# 三层感知机
class MLP(nn.Module):
    def __init__(self):
        super().__init__() # 初始化父类 nn.Module
        self.hidden = nn.Linear(20, 256) # 输入层→隐藏层:20 维 → 256 维的线性变换(权重+偏置)
        self.output = nn.Linear(256, 10) # 隐藏层→输出层:256 维 → 10 维的线性变换(权重+偏置)
        
    def forward(self, x):
        return self.output(F.relu(self.hidden(x)))  # 返回 10 维预测向量

# 调用
net = MLP()
X = torch.randn(size = (2, 20))  # 构造 2 条样本,每条 20 维的随机输入
Y = net(X) # 前向计算,得到 2×10 的输出张量 Y
# 将模型保存道 mlp.params 文件中
# 返回一个 有序字典(OrderedDict),里面只包含 net 中所有可学习参数 的 名称→张量 映射
torch.save(net.state_dict(), 'mlp.params')
# 对原始模型进行备份
clone = MLP()
# 把外部字典的权重 按名字一对一地复制 到 net 的对应参数里,完成 “灌权重” 操作。
clone.load_state_dict(torch.load('mlp.params'))
clone.eval()
MLP(
  (hidden): Linear(in_features=20, out_features=256, bias=True)
  (output): Linear(in_features=256, out_features=10, bias=True)
)
Y_clone = clone(X)
Y_clone == Y
tensor([[True, True, True, True, True, True, True, True, True, True],
        [True, True, True, True, True, True, True, True, True, True]])

posted @ 2025-09-21 23:31  小西贝の博客  阅读(8)  评论(0)    收藏  举报