一、读写文件
1.加载和保存张量
1
2
3
4
5
6
7
8
9
|
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" ) |
现在我们可以将存储在文件中的数据读回内存
1
2
|
x2 = torch.load(path + "x-file" ) x2 |
1
|
tensor([ 0 , 1 , 2 , 3 ]) |
我们可以存储一个张量列表,然后把他们读回内存
1
2
3
4
|
y = torch.zeros( 4 ) torch.save([x, y], path + 'x-file' ) x2, y2 = torch.load(path + 'x-file' ) (x2, y2) |
1
|
(tensor([ 0 , 1 , 2 , 3 ]), tensor([ 0. , 0. , 0. , 0. ])) |
我们甚至可以写入或读取从字符串映射到张量的字典。当我们要读取或写入模型中的所有权重时,这很方便
1
2
3
4
|
mydict = { 'x' : x, 'y' : y} torch.save(mydict, path + 'mydict' ) mydict2 = torch.load( 'mydict' ) mydict2 |
1
|
{ 'x' : tensor([ 0 , 1 , 2 , 3 ]), 'y' : tensor([ 0. , 0. , 0. , 0. ])} |
2.加载和保存模型
保存单个权重向量确实有用,但是如果我们想保存整个模型,并在之后加载他们,单独保存每个向量则会变得很麻烦。毕竟,我们可能有数百个参数分布在各处。深度学习框架提供了内置函数来保存和加载整个网络。需要注意的细节是,这里的保存模型并不是保存整个模型,而只是保存了其中的所有参数。
为了恢复模型,我们需要用代码生成框架,然后从磁盘加载参数。
1
2
3
|
net = MLP() X = torch.randn(size = ( 2 , 20 )) Y = net(X) |
我们将模型的参数存储在一个叫做“mlp.params
”的文件中
1
|
torch.save(net.state_dict(), 'mlp.params' ) |
为了恢复模型,我们实例化了原始多层感知机模型的一个备份。这里我们不需要随机初始化模型参数,而是直接读取文件中的参数
1
2
3
|
clone = MLP() clone.load_state_dict(torch.load( 'mlp.params' )) clone. eval () |
1
2
3
4
|
MLP( (hidden): Linear(in_features = 20 , out_features = 256 , bias = True ) (out): Linear(in_features = 256 , out_features = 10 , bias = True ) ) |
由于两个实例具有相同的模型参数,在输入相同的X时,两个实例的计算结果应该相同
1
2
|
Y_clone = clone(X) Y_clone = = Y |
1
2
|
tensor([[ True , True , True , True , True , True , True , True , True , True ], [ True , True , True , True , True , True , True , True , True , True ]]) |
到此这篇关于基于python介绍pytorch保存和恢复参数的文章就介绍到这了,更多相关pytorch保存和恢复参数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_46311811/article/details/123509031