-
Notifications
You must be signed in to change notification settings - Fork 78
/
report.py
194 lines (145 loc) · 6.48 KB
/
report.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
from keras import callbacks
from text import *
import itertools
import numpy as np
import os
import socket
import sys
import keras.backend as K
from utils import save_model, int_to_text_sequence
class ReportCallback(callbacks.Callback):
def __init__(self, test_func, validdata, model, runtimestr, save):
self.test_func = test_func
self.validdata = validdata
self.validdata_next_val = self.validdata.next_batch()
self.batch_size = validdata.batch_size
self.save = save
# useful if you want to decrease amount in validation
self.valid_test_devide = 1 # 1=no reduce, 10 = 1/10th
#if socket.gethostname().lower() in 'rs-e5550'.lower(): self.valid_test_devide = 50
self.val_best_mean_ed = 0
self.val_best_norm_mean_ed = 0
self.lm = get_model()
self.model = model
self.runtimestr = runtimestr
self.mean_wer_log = []
self.mean_ler_log = []
self.norm_mean_ler_log = []
self.earlystopping = True
self.shuffle_epoch_end = True
self.force_output = False
def validate_epoch_end(self, verbose=0):
originals = []
results = []
count = 0
self.validdata.cur_index = 0 # reset index
if self.valid_test_devide: #check not zero
allvalid = (len(self.validdata.wavpath) // self.validdata.batch_size) // self.valid_test_devide
#make a pass through all the validation data and assess score
for c in range(0, allvalid):
word_batch = next(self.validdata_next_val)[0]
decoded_res = decode_batch(self.test_func,
word_batch['the_input'][0:self.batch_size],
self.batch_size)
for j in range(0, self.batch_size):
# print(c,j)
count += 1
decode_sent = decoded_res[j]
corrected = correction(decode_sent)
label = word_batch['source_str'][j]
#print(label)
if verbose:
cor_wer = wer(label, corrected)
dec_wer = wer(label, decode_sent)
if(dec_wer < 0.4 or cor_wer < 0.4 or self.force_output):
print("\n{}.GroundTruth:{}\n{}.Transcribed:{}\n{}.LMCorrected:{}".format(str(j), label,
str(j), decode_sent,
str(j), corrected))
# print("Sample Decoded WER:{}, Corrected LM WER:{}".format(dec_wer, cor_wer))
originals.append(label)
results.append(corrected)
print("########################################################")
print("Completed Validation Test: WER & LER results")
rates, mean = wers(originals, results)
# print("WER rates :", rates)
lrates, lmean, norm_lrates, norm_lmean = lers(originals, results)
# print("LER rates :", lrates)
# print("LER norm rates:", norm_lrates)
# print("########################################################")
print("Test WER average is :", mean)
print("Test LER average is :", lmean)
print("Test normalised LER is:", norm_lmean)
print("########################################################")
# print("(note both WER and LER use LanguageModel not raw output)")
self.mean_wer_log.append(mean)
self.mean_ler_log.append(lmean)
self.norm_mean_ler_log.append(norm_lmean)
#delete all values?
# del originals, results, count, allvalid
# del word_batch, decoded_res
# del decode_sent,
def on_epoch_end(self, epoch, logs=None):
K.set_learning_phase(0)
if(self.shuffle_epoch_end):
print("shuffle_epoch_end")
self.validdata.genshuffle()
self.validate_epoch_end(verbose=1)
if self.save:
#check to see lowest wer/ler on prev values
if(len(self.mean_wer_log)>2):
lastWER = self.mean_wer_log[-1]
allWER = np.min(self.mean_wer_log[:-1])
lastLER = self.mean_ler_log[-1]
allLER = np.min(self.mean_ler_log[:-1])
if(lastLER < allLER or lastWER < allWER):
savedir = "./checkpoints/epoch/LER-WER-best-{}".format(self.runtimestr)
print("better ler/wer at:", savedir)
if not os.path.isdir(savedir):
os.makedirs(savedir)
try:
save_model(self.model, name=savedir)
except Exception as e:
print("couldn't save error:", e)
#early stopping if VAL WER worse 4 times in a row
if(len(self.mean_wer_log)>5 and self.earlystopping):
if(earlyStopCheck(self.mean_wer_log[-5:])):
print("EARLY STOPPING")
print("Mean WER :", self.mean_wer_log)
print("Mean LER :", self.mean_ler_log)
print("NormMeanLER:", self.norm_mean_ler_log)
sys.exit()
#activate learning phase - incase keras doesn't
K.set_learning_phase(1)
def decode_batch(test_func, word_batch, batch_size):
ret = []
output = test_func([word_batch])[0] #16xTIMEx29 = batch x time x classes
greedy = True
merge_chars = True
for j in range(batch_size): # 0:batch_size
if greedy:
out = output[j]
best = list(np.argmax(out, axis=1))
if merge_chars:
merge = [k for k,g in itertools.groupby(best)]
else:
raise ("not implemented no merge")
else:
pass
raise("not implemented beam")
try:
outStr = int_to_text_sequence(merge)
except Exception as e:
print("Unrecognised character on decode error:", e)
outStr = "DECODE ERROR:"+str(best)
raise("DECODE ERROR2")
ret.append(''.join(outStr))
return ret
def earlyStopCheck(array):
last = array[-1]
rest = array[:-1]
print(last, " vs ", rest)
#in other words- the last element is bigger than all 4 of the previous, therefore early stopping required
if all(i <= last for i in rest):
return True
else:
return False