注意
点击此处下载完整的示例代码
PyTorch 中的 state_dict 是什么¶
创建于: 2020年4月17日 | 最后更新于: 2024年2月6日 | 最后验证于: 2024年11月5日
在 PyTorch 中,torch.nn.Module
模型的可学习参数(即权重和偏置)包含在模型的参数中(通过 model.parameters()
访问)。state_dict
只是一个 Python 字典对象,它将每一层映射到其参数张量。
引言¶
如果你对在 PyTorch 中保存或加载模型感兴趣,那么 state_dict
是一个不可或缺的实体。由于 state_dict
对象是 Python 字典,因此可以轻松地保存、更新、修改和恢复它们,这为 PyTorch 模型和优化器增加了极大的模块化。请注意,只有具有可学习参数(卷积层、线性层等)和已注册 buffer(批归一化的 running_mean)的层才会在模型的 state_dict
中有条目。优化器对象 (torch.optim
) 也有一个 state_dict
,其中包含有关优化器状态以及使用的超参数的信息。在本秘籍中,我们将看到 state_dict
如何与一个简单模型一起使用。
步骤¶
导入加载数据所需的所有库
定义并初始化神经网络
初始化优化器
访问模型和优化器的
state_dict
1. 导入加载数据所需的库¶
对于本秘籍,我们将使用 torch
及其子模块 torch.nn
和 torch.optim
。
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
2. 定义并初始化神经网络¶
为了举例说明,我们将创建一个用于训练图像的神经网络。要了解更多信息,请参阅 定义神经网络 秘籍。
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
print(net)
4. 访问模型和优化器的 state_dict
¶
现在我们已经构建了模型和优化器,我们可以了解它们各自的 state_dict
属性中保留了什么信息。
# Print model's state_dict
print("Model's state_dict:")
for param_tensor in net.state_dict():
print(param_tensor, "\t", net.state_dict()[param_tensor].size())
print()
# Print optimizer's state_dict
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
print(var_name, "\t", optimizer.state_dict()[var_name])
这些信息对于将来保存和加载模型及优化器非常重要。
恭喜!您已成功在 PyTorch 中使用了 state_dict
。