Skip to content

Commit 750fdb9

Browse files
committed
'PyTorch에서 여러 모델을 하나의 파일에 저장하기 & 불러오기' 번역
1 parent 46728d1 commit 750fdb9

File tree

1 file changed

+66
-75
lines changed

1 file changed

+66
-75
lines changed
Lines changed: 66 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,60 @@
11
"""
2-
Saving and loading multiple models in one file using PyTorch
2+
PyTorch에서 여러 모델을 하나의 파일에 저장하기 & 불러오기
33
============================================================
4-
Saving and loading multiple models can be helpful for reusing models
5-
that you have previously trained.
4+
여러 모델을 저장하고 불러오는 것은 이전에 학습했던 모델들을 재사용하는데 도움이 됩니다.
65
7-
Introduction
6+
개요
87
------------
9-
When saving a model comprised of multiple ``torch.nn.Modules``, such as
10-
a GAN, a sequence-to-sequence model, or an ensemble of models, you must
11-
save a dictionary of each model’s state_dict and corresponding
12-
optimizer. You can also save any other items that may aid you in
13-
resuming training by simply appending them to the dictionary.
14-
To load the models, first initialize the models and optimizers, then
15-
load the dictionary locally using ``torch.load()``. From here, you can
16-
easily access the saved items by simply querying the dictionary as you
17-
would expect.
18-
In this recipe, we will demonstrate how to save multiple models to one
19-
file using PyTorch.
20-
21-
Setup
22-
-----
23-
Before we begin, we need to install ``torch`` if it isn’t already
24-
available.
8+
GAN이나 시퀀스-투-시퀀스(sequence-to-sequence model), 앙상블 모델(ensemble of models)과
9+
같이 여러 ``torch.nn.Modules`` 로 구성된 모델을 저장할 때는 각 모델의 state_dict와
10+
해당 옵티마이저(optimizer)의 사전을 저장해야 합니다. 또한, 학습 학습을 재개하는데
11+
필요한 다른 항목들을 사전에 추가할 수 있습니다. 모델들을 불러올 때에는, 먼저
12+
모델들과 옵티마이저를 초기화하고, ``torch.load()`` 를 사용하여 사전을 불러옵니다.
13+
이후 원하는대로 저장한 항목들을 사전에 조회하여 접근할 수 있습니다.
14+
이 레시피에서는 PyTorch를 사용하여 여러 모델들을 하나의 파일에 어떻게 저장하고
15+
불러오는지 살펴보겠습니다.
16+
17+
설정
18+
---------
19+
시작하기 전에 ``torch`` 가 없다면 설치해야 합니다.
2520
2621
::
2722
2823
pip install torch
29-
24+
3025
"""
3126

3227

3328

3429
######################################################################
35-
# Steps
36-
# -----
37-
#
38-
# 1. Import all necessary libraries for loading our data
39-
# 2. Define and intialize the neural network
40-
# 3. Initialize the optimizer
41-
# 4. Save multiple models
42-
# 5. Load multiple models
43-
#
44-
# 1. Import necessary libraries for loading our data
30+
# 단계(Steps)
31+
# -------------
32+
#
33+
# 1. 데이터 불러올 때 필요한 라이브러리들 불러오기
34+
# 2. 신경망을 구성하고 초기화하기
35+
# 3. 옵티마이저 초기화하기
36+
# 4. 여러 모델들 저장하기
37+
# 5. 여러 모델들 불러오기
38+
#
39+
# 1. 데이터 불러올 때 필요한 라이브러리들 불러오기
4540
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
46-
#
47-
# For this recipe, we will use ``torch`` and its subsidiaries ``torch.nn``
48-
# and ``torch.optim``.
49-
#
41+
#
42+
# 이 레시피에서는 ``torch`` 와 여기 포함된 ``torch.nn`` 와 ``torch.optim` 을
43+
# 사용하겠습니다.
44+
#
5045

5146
import torch
5247
import torch.nn as nn
5348
import torch.optim as optim
5449

5550

5651
######################################################################
57-
# 2. Define and intialize the neural network
52+
# 2. 신경망을 구성하고 초기화하기
5853
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
59-
#
60-
# For sake of example, we will create a neural network for training
61-
# images. To learn more see the Defining a Neural Network recipe. Build
62-
# two variables for the models to eventually save.
63-
#
54+
#
55+
# 예를 들어, 이미지를 학습하는 신경망을 만들어보겠습니다. 더 자세한 내용은
56+
# 신경망 구성하기 레시피를 참고해주세요. 모델을 저장할 2개의 변수들을 만듭니다.
57+
#
6458

6559
class Net(nn.Module):
6660
def __init__(self):
@@ -86,25 +80,24 @@ def forward(self, x):
8680

8781

8882
######################################################################
89-
# 3. Initialize the optimizer
83+
# 3. 옵티마이저 초기화하기
9084
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
91-
#
92-
# We will use SGD with momentum to build an optimizer for each model we
93-
# created.
94-
#
85+
#
86+
# 생성한 모델들 각각에 모멘텀(momentum)을 갖는 SGD를 사용하겠습니다.
87+
#
9588

9689
optimizerA = optim.SGD(netA.parameters(), lr=0.001, momentum=0.9)
9790
optimizerB = optim.SGD(netB.parameters(), lr=0.001, momentum=0.9)
9891

9992

10093
######################################################################
101-
# 4. Save multiple models
94+
# 4. 여러 모델들 저장하기
10295
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
103-
#
104-
# Collect all relevant information and build your dictionary.
105-
#
96+
#
97+
# 관련된 모든 정보들을 모아서 사전을 구성합니다.
98+
#
10699

107-
# Specify a path to save to
100+
# 저장할 경로 지정
108101
PATH = "model.pt"
109102

110103
torch.save({
@@ -116,12 +109,11 @@ def forward(self, x):
116109

117110

118111
######################################################################
119-
# 4. Load multiple models
112+
# 5. 여러 모델들 불러오기
120113
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
121-
#
122-
# Remember to first initialize the models and optimizers, then load the
123-
# dictionary locally.
124-
#
114+
#
115+
# 먼저 모델과 옵티마이저를 초기화한 뒤, 사전을 불러오는 것을 기억하십시오.
116+
#
125117

126118
modelA = Net()
127119
modelB = Net()
@@ -136,27 +128,26 @@ def forward(self, x):
136128

137129
modelA.eval()
138130
modelB.eval()
139-
# - or -
131+
# - 또는 -
140132
modelA.train()
141133
modelB.train()
142134

143135

144136
######################################################################
145-
# You must call ``model.eval()`` to set dropout and batch normalization
146-
# layers to evaluation mode before running inference. Failing to do this
147-
# will yield inconsistent inference results.
148-
#
149-
# If you wish to resuming training, call ``model.train()`` to ensure these
150-
# layers are in training mode.
151-
#
152-
# Congratulations! You have successfully saved and loaded multiple models
153-
# in PyTorch.
154-
#
155-
# Learn More
156-
# ----------
157-
#
158-
# Take a look at these other recipes to continue your learning:
159-
#
160-
# - TBD
161-
# - TBD
162-
#
137+
# 추론(inference)을 실행하기 전에 ``model.eval()`` 을 호출하여 드롭아웃(dropout)과
138+
# 배치 정규화 층(batch normalization layer)을 평가(evaluation) 모드로 바꿔야한다는
139+
# 것을 기억하세요. 이것을 빼먹으면 일관성 없는 추론 결과를 얻게 됩니다.
140+
#
141+
# 만약 학습을 계속하길 원한다면 ``model.train()`` 을 호출하여 이 층(layer)들이
142+
# 학습 모드인지 확인(ensure)하세요.
143+
#
144+
# 축하합니다! 지금까지 PyTorch에서 여러 모델들을 저장하고 불러왔습니다.
145+
#
146+
# 더 알아보기
147+
# ------------
148+
#
149+
# 다른 레시피를 둘러보고 계속 배워보세요:
150+
#
151+
# - :doc:`/recipes/recipes/saving_and_loading_a_general_checkpoint`
152+
# - :doc:`/recipes/recipes/saving_multiple_models_in_one_file`
153+
#

0 commit comments

Comments
 (0)