pytorch를 해결하는state_dict () 복제 문제

결론부터 말하다

model.state_dict()는 얕은 복사본으로 되돌아오는 매개 변수는 여전히 네트워크의 훈련에 따라 변화한다.deepcopy(model.state_dict())를 사용하거나 파라미터를 제때에 하드디스크에 서열화해야 한다.
다시 이야기하자면 며칠 전 모델의 교차 검증 훈련을 할 때 모델을 통해state_dict () 는 각 그룹의 교차 검증 모델의 매개 변수를 저장한 후 효과에 따라 정확도가 가장 좋은 모델load를 선택하여 되돌려줍니다. 결과는 매번 마지막 모델입니다. 주소를 보면 저장된state_dict () 는 모두 다른 주소를 가지고 있지만, state_ct() 아래의 각 모델 매개 변수의 주소는 공유된 것이고 나는 in-place 방식으로 모델 매개 변수를 리셋하여 상술한 문제를 초래했다.
추가:pytorch 중state_dict의 이해
PyTorch에서 state_dict는 Python 사전 대상(이 질서 사전에서 키는 각 층의 매개 변수 이름이고value는 각 층의 매개 변수)이며 모델의 학습 가능한 매개 변수(즉 권중과 편차, 그리고 bn 층의 매개 변수)를 포함하는 최적화기 대상(torch.optim)도state_dict, 최적화기 상태와 초파라미터에 대한 정보를 포함합니다.

사실 아래 코드의 출력을 보면 알 수 있을 거예요.


import torch
import torch.nn as nn
import torchvision
import numpy as np
from torchsummary import summary
# 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
# Initialize model
model = TheModelClass()
# Initialize optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=0.001, 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.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [2238501264336, 2238501329800, 2238501330016, 2238501327136, 2238501328576, 2238501329728, 2238501327928, 2238501327064, 2238501330808, 2238501328288]}]
저는 깊이 있는 학문을 접한 샤오바이입니다. 대장부가 저에게 부족한 점을 지적해 주셨으면 좋겠습니다. 이 블로그는 단지 자신의 노트를 위한 것입니다!!!
추가:pytorch 저장모델 타임즈 오류****object has no attribute'state_dict'

클래스 BaseNet을 정의하고 클래스를 실례화합니다.


net=BaseNet()
net 타임즈 오류 저장object has no attribute'state_dict'

torch.save(net.state_dict(), models_dir)
왜냐하면 클래스를 정의할 때 계승nn이 아니기 때문이다.Module 클래스(예:

class BaseNet(object):
  def __init__(self):

클래스 정의를


class BaseNet(nn.Module):
  def __init__(self):
    super(BaseNet, self).__init__()
이상의 개인적인 경험으로 여러분께 참고가 되었으면 좋겠습니다. 또한 많은 응원 부탁드립니다.만약 잘못이 있거나 완전한 부분을 고려하지 않으신다면 아낌없이 가르침을 주시기 바랍니다.

좋은 웹페이지 즐겨찾기