-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
149 lines (119 loc) · 5.01 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import argparse
import etl
import helpers
import random
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from attention_decoder import AttentionDecoderRNN
from encoder import EncoderRNN
# Parse argument for language to train
parser = argparse.ArgumentParser()
parser.add_argument('language')
args = parser.parse_args()
helpers.validate_language(args.language)
teacher_forcing_ratio = .5
clip = 5.
def train(input_var, target_var, encoder, decoder, encoder_opt, decoder_opt, criterion):
# Initialize optimizers and loss
encoder_opt.zero_grad()
decoder_opt.zero_grad()
loss = 0
# Get input and target seq lengths
target_length = target_var.size()[0]
# Run through encoder
encoder_hidden = encoder.init_hidden()
encoder_outputs, encoder_hidden = encoder(input_var, encoder_hidden)
# Prepare input and output variables
decoder_input = Variable(torch.LongTensor([0]))
decoder_input = decoder_input.cuda()
decoder_context = Variable(torch.zeros(1, decoder.hidden_size))
decoder_context = decoder_context.cuda()
decoder_hidden = encoder_hidden
# Scheduled sampling
use_teacher_forcing = random.random() < teacher_forcing_ratio
if use_teacher_forcing:
# Feed target as the next input
for di in range(target_length):
decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input,
decoder_context,
decoder_hidden,
encoder_outputs)
loss += criterion(decoder_output[0], target_var[di])
decoder_input = target_var[di]
else:
# Use previous prediction as next input
for di in range(target_length):
decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input,
decoder_context,
decoder_hidden,
encoder_outputs)
loss += criterion(decoder_output[0], target_var[di])
topv, topi = decoder_output.data.topk(1)
ni = topi[0][0]
decoder_input = Variable(torch.LongTensor([[ni]]))
decoder_input = decoder_input.cuda()
if ni == 1:
break
# Backpropagation
loss.backward()
torch.nn.utils.clip_grad_norm(encoder.parameters(), clip)
torch.nn.utils.clip_grad_norm(decoder.parameters(), clip)
encoder_opt.step()
decoder_opt.step()
return loss.data[0] / target_length
input_lang, output_lang, pairs = etl.prepare_data(args.language)
attn_model = 'general'
hidden_size = 500
n_layers = 2
dropout_p = 0.05
# Initialize models
encoder = EncoderRNN(input_lang.n_words, hidden_size, n_layers)
decoder = AttentionDecoderRNN(attn_model, hidden_size, output_lang.n_words, n_layers, dropout_p=dropout_p)
# Move models to GPU
encoder.cuda()
decoder.cuda()
# Initialize optimizers and criterion
learning_rate = 0.0001
encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)
decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate)
criterion = nn.NLLLoss()
# Configuring training
n_epochs = 100000
plot_every = 200
print_every = 1000
# Keep track of time elapsed and running averages
start = time.time()
plot_losses = []
print_loss_total = 0 # Reset every print_every
plot_loss_total = 0 # Reset every plot_every
# Begin training
for epoch in range(1, n_epochs + 1):
# Get training data for this cycle
training_pair = etl.variables_from_pair(random.choice(pairs), input_lang, output_lang)
input_variable = training_pair[0]
target_variable = training_pair[1]
# Run the train step
loss = train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion)
# Keep track of loss
print_loss_total += loss
plot_loss_total += loss
if epoch == 0:
continue
if epoch % print_every == 0:
print_loss_avg = print_loss_total / print_every
print_loss_total = 0
time_since = helpers.time_since(start, epoch / n_epochs)
print('%s (%d %d%%) %.4f' % (time_since, epoch, epoch / n_epochs * 100, print_loss_avg))
if epoch % plot_every == 0:
plot_loss_avg = plot_loss_total / plot_every
plot_losses.append(plot_loss_avg)
plot_loss_total = 0
# Save our models
torch.save(encoder.state_dict(), '../data/encoder_params_{}'.format(args.language))
torch.save(decoder.state_dict(), '../data/decoder_params_{}'.format(args.language))
torch.save(decoder.attention.state_dict(), '../data/attention_params_{}'.format(args.language))
# Plot loss
helpers.show_plot(plot_losses)