-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.py
231 lines (181 loc) · 7.01 KB
/
decode.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 17 18:33:08 2019
@author: lena
"""
import os
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from masked_cross_entropy import *
from configure import parse_args
from dataset import Dataset
from utils import my_collate_fn
# from Levenshtein import ratio
import matplotlib.pyplot as plt
plt.switch_backend("agg")
import matplotlib.ticker as ticker
import numpy as np
args = parse_args()
def decode(input_seq, input_len, encoder, decoder, in_vocab, out_vocab, max_length=40):
with torch.no_grad():
# input_lengths = [len(input_seq)]
# input_seqs = [indexes_from_sentence(input_lang, input_seq)]
# input_batches = Variable(torch.LongTensor(input_seqs)).transpose(0, 1)
input_seq = Variable(input_seq)
if args.USE_CUDA:
input_seq = input_seq.cuda()
# Set to not-training mode to disable dropout
encoder.train(False)
decoder.train(False)
# Run through encoder
encoder_outputs, encoder_hidden = encoder(input_seq, input_len, None)
# Create starting vectors for decoder
decoder_input = Variable(torch.LongTensor([args.SOS_TOKEN])) # SOS
decoder_hidden = encoder_hidden[
: decoder.n_layers
] # Use last (forward) hidden state from encoder
if args.USE_CUDA:
decoder_input = decoder_input.cuda()
# Store output words and attention states
decoded_chars = []
decoder_attentions = torch.zeros(max_length + 1, max_length + 1)
# Run through decoder
for t in range(max_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_outputs
)
# decoder_attentions[t,:decoder_attention.size(2)] += decoder_attention.squeeze(0).squeeze(0).cpu().data
# Choose top word from output
prob, token_idx = decoder_output.data.topk(1)
tok = token_idx[0][0].item()
if tok == args.EOS_TOKEN:
break
else:
try:
decoded_chars.append(out_vocab[tok])
except KeyError:
pass
# Next input is chosen word
decoder_input = Variable(torch.LongTensor([tok]))
if args.USE_CUDA:
decoder_input = decoder_input.cuda()
# Set back to training mode
encoder.train(True)
decoder.train(True)
return (
" ".join(decoded_chars),
decoder_attentions[: t + 1, : len(encoder_outputs)],
)
def decode_dataset(file_name, encoder, decoder, train_dataset, figs_path):
test_dataset = Dataset(file_name, train=False)
test_dataset.in_vocab = train_dataset.in_vocab
test_dataset.out_vocab = train_dataset.out_vocab
in_vocab = train_dataset.in_vocab[0]
out_vocab = train_dataset.out_vocab[0]
test_iter = DataLoader(
test_dataset,
batch_size=1,
shuffle=False,
num_workers=4,
collate_fn=my_collate_fn,
)
decoded_words = []
attention_counter = 0
for input_seq, input_len, target_seq, _ in test_iter:
decoded_word, attentions = decode(
input_seq, input_len, encoder, decoder, in_vocab, out_vocab
)
# # plot attention
# attention_counter += 1
# if attention_counter < 1000:
# show_attention([in_vocab[int(i)] for i in input_seq],
# decoded_word, attentions, figs_path)
decoded_words.append(
[
" ".join([in_vocab[int(i)] for i in input_seq]),
" ".join([out_vocab[int(i)] for i in target_seq]),
decoded_word,
]
)
print()
return decoded_words
def show_attention(inputs, prediction, attentions, figs_path):
# Set up figure with colorbar
fig = plt.figure()
# fig.subplots_adjust(bottom=2)
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.numpy(), cmap="gray")
fontdict = {"fontsize": 14}
plt.subplots_adjust(bottom=0.1)
plt.subplots_adjust(top=1)
# fig.subplots_adjust(bottom=-1)
fig.colorbar(cax)
# Set up axes
ax.set_xticklabels([""] + inputs + ["</w>"], fontdict=fontdict, rotation=90)
ax.set_yticklabels([""] + prediction.split(" "), fontdict=fontdict)
# Show label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
# plt.show()
plt.savefig(
figs_path + "/" + prediction + ".png", bbox_inches="tight", pad_inches=1
)
plt.close()
# def plot_attention(sentence, predicted_sentence, attention):
# fig = plt.figure(figsize=(10,10))
# ax = fig.add_subplot(1, 1, 1)
# ax.matshow(attention, cmap='viridis') #bone
#
# fontdict = {'fontsize': 14}
#
# ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90)
# ax.set_yticklabels([''] + predicted_sentence.split(' '), fontdict=fontdict)
# plt.show()
# plt.savefig('figs/' + predicted_sentence +'.png')
# plt.close()
def evaluate(decoded_words, lang):
print("Length of test set:\t", str(len(decoded_words)))
wrong_preds = []
right = 0
wrong = 0
# lev_percentage = 0
for word_set in decoded_words:
expected = word_set[1].replace(" ", "").replace("</w>", "")
expected = expected.replace("s_", "").replace("p_", "")
predicted = word_set[2].replace(" ", "").replace("</w>", "")
predicted = predicted.replace("s_", "").replace("p_", "")
# print(expected, predicted)
# similarity = ratio(expected, predicted)
# if similarity == 1.0:
# right += 1
# else:
# wrong += 1
# # print('word_set: ',expected, predicted)
# wrong_preds.append((expected, predicted))
# lev_percentage += similarity
stats = {}
stats["total num"] = len(decoded_words)
stats["no or rights"] = right
stats["no of wrongs"] = wrong
stats["acc"] = right / len(decoded_words)
# stats["lev"] = lev_percentage / len(decoded_words)
print("total num:\t", len(decoded_words))
print("no or rights:\t", str(right))
print("no of wrongs:\t", str(wrong))
print("acc:\t", str(right / len(decoded_words)))
# print("lev:\t", str(lev_percentage / len(decoded_words)))
filename = args.path + "/results/{}-{}.txt".format(
lang, time.strftime("%d%m%y-%H%M%S")
)
with open(filename, "w", encoding="utf-8") as f:
f.write("total num:\t" + str(len(decoded_words)) + "\n")
f.write("no or rights:\t" + str(right) + "\n")
f.write("no of wrongs:\t" + str(wrong) + "\n")
f.write("acc:\t" + str(right / len(decoded_words)) + "\n")
# f.write("lev:\t" + str(lev_percentage / len(decoded_words)) + '\n')
return wrong_preds
# return stats