MCPcopy Index your code
hub / github.com/pytorch/tutorials / train_model

Function train_model

beginner_source/transfer_learning_tutorial.py:149–217  ·  view source on GitHub ↗
(model, criterion, optimizer, scheduler, num_epochs=25)

Source from the content-addressed store, hash-verified

147
148
149def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
150 since = time.time()
151
152 # Create a temporary directory to save training checkpoints
153 with TemporaryDirectory() as tempdir:
154 best_model_params_path = os.path.join(tempdir, 'best_model_params.pt')
155
156 torch.save(model.state_dict(), best_model_params_path)
157 best_acc = 0.0
158
159 for epoch in range(num_epochs):
160 print(f'Epoch {epoch}/{num_epochs - 1}')
161 print('-' * 10)
162
163 # Each epoch has a training and validation phase
164 for phase in ['train', 'val']:
165 if phase == 'train':
166 model.train() # Set model to training mode
167 else:
168 model.eval() # Set model to evaluate mode
169
170 running_loss = 0.0
171 running_corrects = 0
172
173 # Iterate over data.
174 for inputs, labels in dataloaders[phase]:
175 inputs = inputs.to(device)
176 labels = labels.to(device)
177
178 # zero the parameter gradients
179 optimizer.zero_grad()
180
181 # forward
182 # track history if only in train
183 with torch.set_grad_enabled(phase == 'train'):
184 outputs = model(inputs)
185 _, preds = torch.max(outputs, 1)
186 loss = criterion(outputs, labels)
187
188 # backward + optimize only if in training phase
189 if phase == 'train':
190 loss.backward()
191 optimizer.step()
192
193 # statistics
194 running_loss += loss.item() * inputs.size(0)
195 running_corrects += torch.sum(preds == labels.data)
196 if phase == 'train':
197 scheduler.step()
198
199 epoch_loss = running_loss / dataset_sizes[phase]
200 epoch_acc = running_corrects.double() / dataset_sizes[phase]
201
202 print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
203
204 # deep copy the model
205 if phase == 'val' and epoch_acc > best_acc:
206 best_acc = epoch_acc

Callers 1

Calls 4

saveMethod · 0.80
stepMethod · 0.80
modelFunction · 0.70
backwardMethod · 0.45

Tested by

no test coverage detected