加载和保存张量
x = torch.arange(4)
torch.save(x, 'x-file')
x2 = torch.load('x-file')
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.])}
加载和保存模型参数
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') # 保存
# 加载, 但是这个加载 需要这个类存在
clone = MLP()
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) )
import torch
import torch.nn.functional as F
from torch import nn
model = nn.Sequential(nn.Linear(10,100), nn.ReLU(), nn.Linear(100,10))
torch.save(model, 'model.pt')
m = torch.load('model.pt')
i = m(torch.rand(2,10))
print(i)