Last active
January 27, 2020 13:50
-
-
Save aravindpai/753dec4c49586da0ae1c26eb963295d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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