一、读写文件

1.加载和保存张量

import torch
from torch import nn
from torch.nn import functional as f
import os

path = os.path.join(os.getcwd(), "")

x = torch.arange(4)
torch.save(x, path + "x-file")

现在我们可以将存储在文件中的数据读回内存

x2 = torch.load(path + "x-file")
x2
tensor([0, 1, 2, 3])

我们可以存储一个张量列表,然后把他们读回内存

y = torch.zeros(4)
torch.save([x, y], path + 'x-file')
x2, y2 = torch.load(path + 'x-file')
(x2, y2)
(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))

我们甚至可以写入或读取从字符串映射到张量的字典。当我们要读取或写入模型中的所有权重时,这很方便

mydict = {'x': x, 'y': y}
torch.save(mydict, path + 'mydict')
mydict2 = torch.load('mydict')
mydict2
{'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}

2.加载和保存模型

保存单个权重向量确实有用,但是如果我们想保存整个模型,并在之后加载他们,单独保存每个向量则会变得很麻烦。毕竟,我们可能有数百个参数分布在各处。深度学习框架提供了内置函数来保存和加载整个网络。需要注意的细节是,这里的保存模型并不是保存整个模型,而只是保存了其中的所有参数。
为了恢复模型,我们需要用代码生成框架,然后从磁盘加载参数。

net = mlp()
x = torch.randn(size=(2, 20))
y = net(x)

我们将模型的参数存储在一个叫做“mlp.params”的文件中

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)
  (out): linear(in_features=256, out_features=10, bias=true)
)

由于两个实例具有相同的模型参数,在输入相同的x时,两个实例的计算结果应该相同

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]])

到此这篇关于基于python介绍pytorch保存和恢复参数的文章就介绍到这了,更多相关pytorch保存和恢复参数内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!