Skip to content

Instantly share code, notes, and snippets.

@aravindpai
Last active January 27, 2020 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aravindpai/753dec4c49586da0ae1c26eb963295d1 to your computer and use it in GitHub Desktop.
Save aravindpai/753dec4c49586da0ae1c26eb963295d1 to your computer and use it in GitHub Desktop.
def train(model, iterator, optimizer, criterion):
#initialize every epoch
epoch_loss = 0
epoch_acc = 0
#set the model in training phase
model.train()
for batch in iterator:
#resets the gradients after every batch
optimizer.zero_grad()
#retrieve text and no. of words
text, text_lengths = batch.text
#convert to 1D tensor
predictions = model(text, text_lengths).squeeze()
#compute the loss
loss = criterion(predictions, batch.label)
#compute the binary accuracy
acc = binary_accuracy(predictions, batch.label)
#backpropage the loss and compute the gradients
loss.backward()
#update the weights
optimizer.step()
#loss and accuracy
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment