1. 모델 저장하기
import copy
best_model = copy.deepcopy(model.state_dict())
torch.save(best_model, 'best.pth')
2. 모델 로드하기
단 여기서 model param이 앞에 정의되어있어야 함
model.load_state_dict(torch.load('best.pth'))
이렇게 로드하면
FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
model.load_state_dict(torch.load('best.pth'))
이런 경고문이 뜬다.
이 경고문을 피하려면 아래와 같이 하면 해결된다.
# 가중치만 로드
state_dict = torch.load('best.pth', weights_only=True)
model.load_state_dict(state_dict)
model.eval() # 추론 모드로 전환
++ 모델 클래서 정의없이 저장 및 로드하기
# 모델 저장 시
model_scripted = torch.jit.script(model)
model_scripted.save('model_scripted.pt')
# 모델 로드 시 (클래스 정의 필요 없음)
model = torch.jit.load('model_scripted.pt')
model.eval()
728x90
반응형
'Programming > Python' 카테고리의 다른 글
GELU, Gaussian Error Linear Unit (0) | 2024.11.22 |
---|---|
트랜스포머 대체재 mamba? (0) | 2024.06.21 |
240424강의자료 제안 (0) | 2024.04.24 |
Generative Models(생성 모델), GAN (1) | 2024.02.27 |
Recurrent Neural Networks(RNN), Transformer (1) | 2024.02.27 |