目录
1.保存和加载张量
存储一个张量
import torch
from torch import nn
from torch.nn import functional as F
# 保存张量
x = torch.arange(4)
torch.save(x,'x-file')
# 加载张量
x2 = torch.load('x-file')
x2 # tensor([0, 1, 2, 3])
存储一个张量列表
x = torch.arange(4)
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.]))
写入或读取从字符串映射到张量的字典
x = torch.arange(4)
y = torch.zeros(4)
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__()
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)
# 保存该net模型的参数到'mlp.params'文件中
torch.save(net.state_dict(),'mlp.params')
# 为了恢复模型,我们实例化了原始多层感知机模型的一个备份。
# 我们没有随机初始化模型参数,而是直接读取文件中存储的参数
clone = MLP() # 也要保证模型是一致的
# 加载模型参数
clone.load_state_dict(torch.load('mlp.params'))
clone.eval()
# 验证net和clone的参数是否相同
Y_clone = clone(X)
Y == Y_clone
# 若输出值相同,说明参数值也相同
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]])