大家好:
之前比较困惑torch.save(net, 'example.pt')保存的权重文件类型,无法查看训练好的权重参数问题,这次进行一次总结。
首先,torch.save()保存两种模型文件,有如下两种方式:
import torch
#1.只保存训练好的模型各层参数
torch.save(net.state_dict(), 'example1.pt') #--net即定义的网络模型
#2.将模型结构与训练好的模型各层参数一起保存
torch.save(net, 'example2.pt') #--net即定义的网络模型
针对两种方式,这里在不用创建网络模型实例的情况下,实现训练好的模型参数的查看:
#1保存方式--只保存了训练好的模型各层参数
file1 = torch.load('./example1.pt')
print(file1)
#2保存方式--网络结构与训练好的模型各层参数均保存
file2 = torch.load('./example2.pt')
print(file2[1]._parameters)
这里以softmax模型为例,只有简单的两层,第一层是Flatten,第二层是Linear,即:
from torch import nn
#随便举的例子
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))
这里就简单训练了一下,然后得到了两种保存方式保存的.pt文件,按照上述查看模型参数的方式得到如下输出:
'''第1种保存方式'''
#1保存方式--只保存了训练好的模型各层参数
file1 = torch.load('./example1.pt')
print(file1)
#以下是打印结果
OrderedDict([('1.weight', tensor([[-0.0099, -0.0036, 0.0050, ..., -0.0308, -0.0038, -0.0131],
[-0.0085, -0.0198, -0.0064, ..., -0.0054, 0.0053, -0.0058],
[ 0.0062, -0.0126, 0.0087, ..., 0.0498, 0.0205, 0.0077],
...,
[-0.0100, -0.0026, -0.0107, ..., 0.0151, 0.0047, 0.0054],
[-0.0089, -0.0015, -0.0014, ..., -0.0441, -0.0087, 0.0006],
[ 0.0139, -0.0002, -0.0058, ..., 0.0104, -0.0066, 0.0095]])), ('1.bias', tensor([ 0.2636, -0.3011, -0.0763, 0.1720, -0.9091, 1.9251, 0.4222, -0.0917,
-0.4364, -0.9618]))])
'''第2种保存方式'''
#2保存方式--网络结构与训练好的模型各层参数均保存
file2 = torch.load('./example2.pt')
print(file2[1]._parameters)
#以下是打印结果:
OrderedDict([('weight', Parameter containing:
tensor([[-0.0099, -0.0036, 0.0050, ..., -0.0308, -0.0038, -0.0131],
[-0.0085, -0.0198, -0.0064, ..., -0.0054, 0.0053, -0.0058],
[ 0.0062, -0.0126, 0.0087, ..., 0.0498, 0.0205, 0.0077],
...,
[-0.0100, -0.0026, -0.0107, ..., 0.0151, 0.0047, 0.0054],
[-0.0089, -0.0015, -0.0014, ..., -0.0441, -0.0087, 0.0006],
[ 0.0139, -0.0002, -0.0058, ..., 0.0104, -0.0066, 0.0095]],
requires_grad=True)), ('bias', Parameter containing:
tensor([ 0.2636, -0.3011, -0.0763, 0.1720, -0.9091, 1.9251, 0.4222, -0.0917,
-0.4364, -0.9618], requires_grad=True))])
可以看出,两种方式保存的权重文件,保存的训练好的参数是一致的。
通过如下方式查看各个保存文件的属性:
print(file1.__dict__)
就能够具体查看各个权重文件的属性以及属性值了。
通过上述方式就可以只通过权重文件查看权重参数,而不需要实例化模型啦。