天天看點

optimizer.load_state_dict()參考連結

參考連結

在PyTorch中,torch.nn.Module的可學習參數(即權重和偏差),子產品模型包含在model’s參數中(通過model.parameters()通路)。state_dict是個簡單的Python dictionary對象,它将每個層映射到它的參數張量。

注意,隻有具有可學習參數的層(卷積層、線性層等)才有model’s state_dict中的條目。優化器對象(connector .optim)也有一個state_dict,其中包含關于優化器狀态以及所使用的超參數的資訊。

import torch
import torch.nn as nn
import torch.nn.functional as F
 #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 farward(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
# Initialize model
model=TheModelClass()
# Initialize optimizer
optimizer=torch.optim.SGD(model.parameters(),lr=1e-4,momentum=0.9)

print("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("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])```

           

結果:

Model's state_dict:
conv1.weight     torch.Size([6, 3, 5, 5])
conv1.bias   torch.Size([6])
conv2.weight     torch.Size([16, 6, 5, 5])
conv2.bias   torch.Size([16])
fc1.weight   torch.Size([120, 400])
fc1.bias     torch.Size([120])
fc2.weight   torch.Size([84, 120])
fc2.bias     torch.Size([84])
fc3.weight   torch.Size([10, 84])
fc3.bias     torch.Size([10])
optimizer's state_dict:
state    {}
param_groups     [{'lr': 0.0001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [1310469552240, 1310469552384, 1310469552456, 1310469552528, 1310469552600, 1310469552672, 1310469552744, 1310469552816, 1310469552888, 1310469552960]}]
           

繼續閱讀