본문 바로가기
책&강의 학습/올인원 패키지 :딥러닝&인공지능

[패스트캠퍼스 수강 후기] 인공지능강의 100% 환급 챌린지 19회차 미션

by 소한보 2020. 7. 17.

Part3-24 Pytorch - 05. Learning Rate Schedule

Learning Rate Schedule

로컬미니마에 빠지는 오류 방지

from torch.optim.lr_scheduler import ReduceLROnPlateau
 # factor 얼마나 줄여나갈 것인지 
 # patience 얼마나 참고 기다릴것인지 
scheduler = ReduceLROnPlateau(optimizer, mode='max', factor=0.1, patience=0, verbose=True)
 #training 부분에 추가 
cheduler.step(accuracy, epoch)

Part3-25 Pytorch - 06. save and load model

저장방식이 조금씩 다르기 때문에 저장하는 법 학습
저장확장명을 주로 'pt'사용

weight만 저장

전이학습 등 커스터마이즈 하기 좋기 때문에 공식홈페이지에서 추천

 #모델 저장
save_path = 'model_weight.pt'
torch.save(model.state_dict(), save_path)
 #모델 로드 
model = Net().to(device)
weight_dict = torch.load(save_path)
weight_dict.keys()
>>> odict_keys(['conv1.weight', 'conv1.bias', 'conv2.weight', 'conv2.bias', 'fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias'])
weight_dict['conv1.weight'].shape
>>> torch.Size([20, 1, 5, 5])

 #weight를 불러오기만 했고 아직 모델에 적용한 것이 아님 
 #모델에 적용
model.load_state_dict(weight_dict)
>>> <All keys matched successfully>
model.eval()
>>> Net(
  (conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(20, 50, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=800, out_features=500, bias=True)
  (fc2): Linear(in_features=500, out_features=10, bias=True)
)

모델까지 통째로 저장

모델설계를 다시 해야하는 번거로움을 방지하기 위해서 모델까지 저장

save_path = 'model.pt'
torch.save(model, save_path)
 # 통째로 저장했기때문에 load하면 모델임
model = torch.load(save_path)
model.eval()
>>> Net(
  (conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(20, 50, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=800, out_features=500, bias=True)
  (fc2): Linear(in_features=500, out_features=10, bias=True)
)

체크포인트로 모델 저장하고 다시 학습하기

checkpoint_path = 'checkpoint.pt'
 # epoch, model_state_dict 등 까지도 같이 저장
torch.save({
            'epoch': epoch,
            'model_state_dict': model.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(), #학습을 이어서 할때는 옵티마이저도 state_dict로 저장
            'loss': loss
            }, checkpoint_path)
 # 모델 로드
model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum)

checkpoint = torch.load(checkpoint_path)
checkpoint.keys()
>>> dict_keys(['epoch', 'model_state_dict', 'optimizer_state_dict', 'loss'])

model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
epoch = checkpoint['epoch']
loss = checkpoint['loss']

텐서플로우와 파이토치

텐서플로우가 사용방법이 다양하기때문에 설명할 것이 많음
필요에 따라서 텐서플로우, 파이토치를 사용하면 됨

딥러닝/인공지능 올인원 패키지 Online

댓글