MCPcopy Create free account
hub / github.com/pytorch/tutorials / train

Function train

beginner_source/knowledge_distillation_tutorial.py:174–198  ·  view source on GitHub ↗
(model, train_loader, epochs, learning_rate, device)

Source from the content-addressed store, hash-verified

172#
173
174def train(model, train_loader, epochs, learning_rate, device):
175 criterion = nn.CrossEntropyLoss()
176 optimizer = optim.Adam(model.parameters(), lr=learning_rate)
177
178 model.train()
179
180 for epoch in range(epochs):
181 running_loss = 0.0
182 for inputs, labels in train_loader:
183 # inputs: A collection of batch_size images
184 # labels: A vector of dimensionality batch_size with integers denoting class of each image
185 inputs, labels = inputs.to(device), labels.to(device)
186
187 optimizer.zero_grad()
188 outputs = model(inputs)
189
190 # outputs: Output of the network for the collection of images. A tensor of dimensionality batch_size x num_classes
191 # labels: The actual labels of the images. Vector of dimensionality batch_size
192 loss = criterion(outputs, labels)
193 loss.backward()
194 optimizer.step()
195
196 running_loss += loss.item()
197
198 print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader)}")
199
200def test(model, test_loader, device):
201 model.to(device)

Calls 3

stepMethod · 0.80
modelFunction · 0.70
backwardMethod · 0.45

Tested by

no test coverage detected