pytorch 状态字典:state_dict

pytorch 中的 state_dict 是一个简单的python的字典对象,将每一层与它的对应参数建立映射关系.(如model的每一层的weights及偏置等等)

(注意,只有那些参数可以训练的layer才会被保存到模型的state_dict中,如卷积层,线性层等等)

优化器对象Optimizer也有一个state_dict,它包含了优化器的状态以及被使用的超参数(如lr, momentum,weight_decay等)

 

备注:

1) state_dict是在定义了model或optimizer之后pytorch自动生成的,可以直接调用.常用的保存state_dict的格式是".pt"或'.pth'的文件,即下面命令的 PATH="./***.pt"

torch.save(model.state_dict(), PATH)

2) load_state_dict 也是model或optimizer之后pytorch自动具备的函数,可以直接调用

model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
model.eval()

注意:model.eval() 的重要性,在2)中最后用到了model.eval(),是因为,只有在执行该命令后,"dropout层"及"batch normalization层"才会进入 evalution 模态. 而在"训练(training)模态"与"评估(evalution)模态"下,这两层有不同的表现形式.

-------------------------------------------------------------------------------------------------------------------------------

模态字典(state_dict)的保存(model是一个网络结构类的对象)

1.1)仅保存学习到的参数,用以下命令

    torch.save(model.state_dict(), PATH)

1.2)加载model.state_dict,用以下命令

    model = TheModelClass(*args, **kwargs)
    model.load_state_dict(torch.load(PATH))
    model.eval()

    备注:model.load_state_dict的操作对象是 一个具体的对象,而不能是文件名

-----------

2.1)保存整个model的状态,用以下命令

    torch.save(model,PATH)

2.2)加载整个model的状态,用以下命令:

          # Model class must be defined somewhere

    model = torch.load(PATH)

    model.eval()

--------------------------------------------------------------------------------------------------------------------------------------

state_dict 是一个python的字典格式,以字典的格式存储,然后以字典的格式被加载,而且只加载key匹配的项

----------------------------------------------------------------------------------------------------------------------

如何仅加载某一层的训练的到的参数(某一层的state)

If you want to load parameters from one layer to another, but some keys do not match, simply change the name of the parameter keys in the state_dict that you are loading to match the keys in the model that you are loading into.

conv1_weight_state = torch.load('./model_state_dict.pt')['conv1.weight']

--------------------------------------------------------------------------------------------

加载模型参数后,如何设置某层某参数的"是否需要训练"(param.requires_grad)
 

for param in list(model.pretrained.parameters()):
    param.requires_grad = False

注意: requires_grad的操作对象是tensor.

疑问:能否直接对某个层直接之用requires_grad呢?例如:model.conv1.requires_grad=False

回答:经测试,不可以.model.conv1 没有requires_grad属性.

 

---------------------------------------------------------------------------------------------

全部测试代码:
 

#-*-coding:utf-8-*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
 
 
 
# define model
class TheModelClass(nn.Module):
    def __init__(self):
        super(TheModelClass,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
 
# initial model
model = TheModelClass()
 
#initialize the optimizer
optimizer = optim.SGD(model.parameters(),lr=0.001,momentum=0.9)
 
# print the model's state_dict
print("model's state_dict:")
for param_tensor in model.state_dict():
    print(param_tensor,'\t',model.state_dict()[param_tensor].size())
 
print("\noptimizer's state_dict")
for var_name in optimizer.state_dict():
    print(var_name,'\t',optimizer.state_dict()[var_name])
 
print("\nprint particular param")
print('\n',model.conv1.weight.size())
print('\n',model.conv1.weight)
 
print("------------------------------------")
torch.save(model.state_dict(),'./model_state_dict.pt')
# model_2 = TheModelClass()
# model_2.load_state_dict(torch.load('./model_state_dict'))
# model.eval()
# print('\n',model_2.conv1.weight)
# print((model_2.conv1.weight == model.conv1.weight).size())
## 仅仅加载某一层的参数
conv1_weight_state = torch.load('./model_state_dict.pt')['conv1.weight']
print(conv1_weight_state==model.conv1.weight)
 
model_2 = TheModelClass()
model_2.load_state_dict(torch.load('./model_state_dict.pt'))
model_2.conv1.requires_grad=False
print(model_2.conv1.requires_grad)
print(model_2.conv1.bias.requires_grad)

转自:https://blog.csdn.net/strive_for_future/article/details/83240081

  • 9
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 函数。 PyTorch中的load_state_dict()函数可以把一个保存的模型参数加载到模型中。它可以把模型的参数从一个字典对象中加载到模型中,也可以把参数从一个保存的文件中加载到模型中。这个函数可以帮助用户从模型的训练中恢复,从而可以继续训练模型或者使用模型进行预测。 ### 回答2: pytorch的load_state_dict()函数是用于加载预训练模型参数的方法。它接收一个state_dict参数,state_dict是一个Python字典对象,包含了模型的参数和对应的权重。load_state_dict()方法将这些参数加载到指定的模型中。 PyTorch模型通过一个有序字典对象来存储所有的模型参数,包括模型的可训练和不可训练参数。state_dict中的key对应于模型的每个参数的名称,value则存储了相应参数的权重。 当我们进行模型训练,并在某个epoch达到最佳模型时,我们可以使用state_dict将这些训练好的参数保存下来。之后,当我们需要再次使用这个模型时,可以使用load_state_dict()加载这些保存下来的参数,以便于我们继续模型训练或进行预测。 使用load_state_dict()的基本步骤是: 1. 定义一个与要加载参数的模型相同的模型对象; 2. 调用load_state_dict()方法并传入保存下来的state_dict; 3. 通过调用加载参数的模型对象就可以使用保存下来的参数进行训练或者进行预测。 在加载参数时,需要注意参数的名称和结构应该与之前保存的参数保持一致,否则会导致参数加载失败。可以通过指定strict=False来允许一部分参数不存在。 除了加载整个模型的参数,还可以通过使用load_state_dict()来加载模型的部分参数,例如只加载某个层的参数。 总而言之,pytorch的load_state_dict()函数是一个用于加载预训练模型参数的重要工具,可以帮助我们在训练和预测中有效地管理和使用模型的权重。 ### 回答3: pytorch 中的 load_state_dict() 是一个模型加载函数,用于加载预训练模型的参数。它是一个模型类的方法,可以通过调用模型对象的 load_state_dict() 函数来使用。 load_state_dict() 函数需要传入一个参数,即预训练模型状态字典state_dict)。状态字典是一个 Python 字典,它将每个模型的参数名称映射到其对应的参数值。模型状态字典可以通过模型对象的 state_dict() 函数来获取。 当我们在 PyTorch 中训练一个模型时,优化器会保存模型的参数状态以及优化器的状态,方便下次恢复训练。load_state_dict() 函数将会加载预训练模型的参数状态字典到当前模型中,以便我们可以从预训练模型中复制参数值。 在调用 load_state_dict() 函数之前,我们需要确保预训练模型和当前模型的网络结构是一致的,即它们具有相同的模型参数名字和参数形状。如果预训练模型和当前模型的网络结构不一致,load_state_dict() 函数会抛出错误。 一般来说,加载预训练模型的过程分为两个步骤。首先,我们创建一个空的模型对象,并根据预训练模型的网络结构进行初始化。然后,我们调用 load_state_dict() 函数来加载预训练模型的参数。 总之,pytorch 中的 load_state_dict() 函数是一个方便的模型加载函数,它可以加载预训练模型的参数。我们可以使用它来快速加载训练好的模型,以便进行推理、迁移学习等任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值