17读写文件
import torch
import os
from torch import nn
from torch.nn import functional as F
file_path = '..\\limuPytorch\\module\\'
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
x = torch.arange(4)
torch.save(x, file_path + 'x-file')
x2 = torch.load(file_path + 'x-file')
print(x2)
"""
tensor([0, 1, 2, 3])
"""
y = torch.zeros(4)
torch.save([x, y],file_path + 'x-files')
x2, y2 = torch.load(file_path + 'x-files')
print(x2,y2)
"""
tensor([0, 1, 2, 3]) tensor([0., 0., 0., 0.])
"""
mydict = {'x': x, 'y': y}
torch.save(mydict, file_path + 'mydict')
mydict2 = torch.load(file_path + 'mydict')
print(mydict2)
"""
{'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}
"""
"""
保存单个权重向量(或其他张量)确实有用,
但是如果我们想保存整个模型,并在以后加载它们,
单独保存每个向量则会变得很麻烦。
毕竟,我们可能有数百个参数散布在各处。
因此,深度学习框架提供了内置函数来保存和加载整个网络。
需要注意的一个重要细节是,这将保存模型的参数而不是保存整个模型。
例如,如果我们有一个3层多层感知机,我们需要单独指定架构。
因为模型本身可以包含任意代码,所以模型本身难以序列化。
因此,为了恢复模型,我们需要用代码生成架构, 然后从磁盘加载参数。
"""
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(), file_path + 'mlp.params')
clone = MLP()
clone.load_state_dict(torch.load(file_path + 'mlp.params'))
print(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)
print(Y_clone == Y)
"""
tensor([[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True]])
"""