Skip to content

Instantly share code, notes, and snippets.

@Lexie88rus
Created August 30, 2019 23:56
Show Gist options
  • Save Lexie88rus/37ed928d2a12bdcd0623bee0880eb955 to your computer and use it in GitHub Desktop.
Save Lexie88rus/37ed928d2a12bdcd0623bee0880eb955 to your computer and use it in GitHub Desktop.
Training procedure for LSTM model
# Define training procedure
def train(sequence, target, device):
# Move tensors to device
hidden = rnn.initHidden(device)
sequence = sequence.to(device)
target = target.to(device)
rnn.zero_grad()
# Forward step
for i in range(sequence.size()[0]):
output, hidden = rnn(sequence[i], hidden)
output, hidden = rnn(sequence[i], hidden)
loss = criterion(output, indexFromTensor(target).to(device))
loss.backward()
# Add parameters' gradients to their values, multiplied by learning rate
for p in rnn.parameters():
p.data.add_(-learning_rate, p.grad.data)
return output, loss.item()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment