forked from cyprienruffino/CTCModel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CTCModel.py
1185 lines (936 loc) · 47 KB
/
CTCModel.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import keras.backend as K
import tensorflow as tf
import numpy as np
import os
from keras import Input
from keras.engine import Model
from keras.layers import Lambda
from keras.models import model_from_json
import pickle
from tensorflow.python.ops import ctc_ops as ctc
from keras.utils import Sequence, GeneratorEnqueuer, OrderedEnqueuer
import warnings
from keras.utils.generic_utils import Progbar
#from ocr_ctc.utils.utils_analysis import tf_edit_distance
#from ocr_ctc.utils.utils_keras import Kreshape_To1D
from keras.preprocessing import sequence
"""
authors: Yann Soullard, Cyprien Ruffino (2017)
LITIS lab, university of Rouen (France)
The CTCModel class extends the Keras Model for the use of the Connectionist Temporal Classification (CTC)
One makes use of the CTC proposed in tensorflow. Thus CTCModel can only be used with the backend tensorflow.
The CTCModel structure is composed of 3 branches. Each branch is a Keras Model:
- One for computing the CTC loss (model_train)
- One for predicting using the ctc_decode method (model_pred)
- One for analyzing (model_eval) that computes the Label Error Rate (LER) and Sequence Error Rate (SER).
In a Keras Model, x is the input features and y the labels.
Here, x data are of the form [input_sequences, label_sequences, inputs_lengths, labels_length]
and y are not used as in a Keras Model (this is an array which is not considered,
the labeling is given in the x data structure).
"""
class CTCModel:
def __init__(self, inputs, outputs, greedy=True, beam_width=100, top_paths=1, charset=None):
"""
Initialization of a CTC Model.
:param inputs: Input layer of the neural network
outputs: Last layer of the neural network before CTC (e.g. a TimeDistributed Dense)
greedy, beam_width, top_paths: Parameters of the CTC decoding (see ctc decoding tensorflow for more details)
charset: labels related to the input of the CTC approach
"""
self.model_train = None
self.model_pred = None
self.model_eval = None
self.inputs = inputs
self.outputs = outputs
self.greedy = greedy
self.beam_width = beam_width
self.top_paths = top_paths
self.charset = charset
def compile(self, optimizer):
"""
Configures the CTC Model for training.
There is 3 Keras models:
- one for training
- one for predicting
- one for analyzing
Lambda layers are used to compute:
- the CTC loss function
- the CTC decoding
- the CTC evaluation
:param optimizer: The optimizer used during training
"""
# Others inputs for the CTC approach
labels = Input(name='labels', shape=[None])
input_length = Input(name='input_length', shape=[1])
label_length = Input(name='label_length', shape=[1])
# Lambda layer for computing the loss function
loss_out = Lambda(self.ctc_loss_lambda_func, output_shape=(1,), name='CTCloss')(
self.outputs + [labels, input_length, label_length])
# Lambda layer for the decoding function
out_decoded_dense = Lambda(self.ctc_complete_decoding_lambda_func, output_shape=(None, None), name='CTCdecode', arguments={'greedy': self.greedy,
'beam_width': self.beam_width, 'top_paths': self.top_paths},dtype="float32")(
self.outputs + [input_length])
# Lambda layer to perform an analysis (CER and SER)
out_analysis = Lambda(self.ctc_complete_analysis_lambda_func, output_shape=(None,), name='CTCanalysis',
arguments={'greedy': self.greedy,
'beam_width': self.beam_width, 'top_paths': self.top_paths},dtype="float32")(
self.outputs + [labels, input_length, label_length])
# create Keras models
self.model_init = Model(inputs=self.inputs, outputs=self.outputs)
self.model_train = Model(inputs=self.inputs + [labels, input_length, label_length], outputs=loss_out)
self.model_pred = Model(inputs=self.inputs + [input_length], outputs=out_decoded_dense)
self.model_eval = Model(inputs=self.inputs + [labels, input_length, label_length], outputs=out_analysis)
# Compile models
self.model_train.compile(loss={'CTCloss': lambda yt, yp: yp}, optimizer=optimizer)
self.model_pred.compile(loss={'CTCdecode': lambda yt, yp: yp}, optimizer=optimizer)
self.model_eval.compile(loss={'CTCanalysis': lambda yt, yp: yp}, optimizer=optimizer)
def get_model_train(self):
"""
:return: Model used for training using the CTC approach
"""
return self.model_train
def get_model_pred(self):
"""
:return: Model used for testing using the CTC approach
"""
return self.model_pred
def get_model_eval(self):
"""
:return: Model used for evaluating using the CTC approach
"""
return self.model_eval
def get_loss_on_batch(self, inputs, verbose=False):
"""
Computation the loss
inputs is a list of 4 elements:
x_features, y_label, x_len, y_len (similarly to the CTC in tensorflow)
:return: Probabilities (output of the TimeDistributedDense layer)
"""
x = inputs[0]
x_len = inputs[2]
y = inputs[1]
y_len = inputs[3]
no_lab = True if 0 in y_len else False
if no_lab is False:
loss_data = self.model_train.predict_on_batch([x, y, x_len, y_len], verbose=verbose)
loss = np.sum(loss_data)
return loss, loss_data
def get_loss(self, inputs, verbose=False):
"""
Computation the loss
inputs is a list of 4 elements:
x_features, y_label, x_len, y_len (similarly to the CTC in tensorflow)
:return: Probabilities (output of the TimeDistributedDense layer)
"""
x = inputs[0]
x_len = inputs[2]
y = inputs[1]
y_len = inputs[3]
batch_size = x.shape[0]
no_lab = True if 0 in y_len else False
if no_lab is False:
loss_data = self.model_train.predict([x, y, x_len, y_len], batch_size=batch_size, verbose=verbose)
loss = np.sum(loss_data)
return loss, loss_data
def get_loss_generator(self, generator, nb_batchs, verbose=False):
"""
The generator must provide x as [input_sequences, label_sequences, inputs_lengths, labels_length]
:return: loss on the entire dataset_manager and the loss per data
"""
loss_per_data = []
for k in range(nb_batchs):
data = next(generator)
x = data[0][0]
x_len = data[0][2]
y = data[0][1]
y_len = data[0][3]
batch_size = x.shape[0]
no_lab = True if 0 in y_len else False
if no_lab is False:
loss_data = self.model_train.predict([x, y, x_len, y_len], batch_size=batch_size, verbose=verbose)
loss_per_data += [elmt[0] for elmt in loss_data]
loss = np.sum(loss_per_data)
return loss, loss_per_data
def get_probas_generator(self, generator, nb_batchs, verbose=False):
"""
Get the probabilities of each label at each time of an observation sequence (matrix T x D)
This is the output of the softmax function after the recurrent layers (the input of the CTC computations)
Computation is done in batches using a generator. This function does not exist in a Keras Model.
:return: A set of probabilities for each sequence and each time frame, one probability per label + the blank
(this is the output of the TimeDistributed Dense layer, the blank label is the last probability)
"""
probs_epoch = []
for k in range(nb_batchs):
data = next(generator)
x = data[0][0]
x_len = data[0][2]
batch_size = x.shape[0]
# Find the output of the softmax function
probs = self.model_init.predict(x, batch_size=batch_size, verbose=verbose)
# Select the outputs that do not refer to padding
probs_epoch += [np.asarray(probs[data_idx, :x_len[data_idx][0], :]) for data_idx in range(batch_size)]
return probs_epoch
def get_probas_on_batch(self, inputs, verbose=False):
"""
Get the probabilities of each label at each time of an observation sequence (matrix T x D)
This is the output of the softmax function after the recurrent layers (the input of the CTC computations)
Computation is done for a batch. This function does not exist in a Keras Model.
:return: A set of probabilities for each sequence and each time frame, one probability per label + the blank
(this is the output of the TimeDistributed Dense layer, the blank label is the last probability)
"""
x = inputs[0]
x_len = inputs[2]
batch_size = x.shape[0]
# Find the output of the softmax function
probs = self.model_init.predict(x, batch_size=batch_size, verbose=verbose)
# Select the outputs that do not refer to padding
probs_epoch = [np.asarray(probs[data_idx, :x_len[data_idx][0], :]) for data_idx in range(batch_size)]
return probs_epoch
def get_probas(self, inputs, batch_size, verbose=False):
"""
Get the probabilities of each label at each time of an observation sequence (matrix T x D)
This is the output of the softmax function after the recurrent layers (the input of the CTC computations)
Computation is done for a batch. This function does not exist in a Keras Model.
:return: A set of probabilities for each sequence and each time frame, one probability per label + the blank
(this is the output of the TimeDistributed Dense layer, the blank label is the last probability)
"""
x = inputs[0]
x_len = inputs[2]
# Find the output of the softmax function
probs = self.model_init.predict(x, batch_size=batch_size, verbose=verbose)
# Select the outputs that do not refer to padding
probs_epoch = [np.asarray(probs[data_idx, :x_len[data_idx][0], :]) for data_idx in range(batch_size)]
return probs_epoch
def fit_generator(self, generator,
steps_per_epoch,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
class_weight=None,
max_q_size=10,
workers=1,
pickle_safe=False,
initial_epoch=0):
"""
Model training on data yielded batch-by-batch by a Python generator.
The generator is run in parallel to the model, for efficiency.
For instance, this allows you to do real-time data augmentation on images on CPU in parallel to training your model on GPU.
A major modification concerns the generator that must provide x data of the form:
[input_sequences, label_sequences, inputs_lengths, labels_length]
(in a similar way than for using CTC in tensorflow)
:param: See keras.engine.Model.fit_generator()
:return: A History object
"""
out = self.model_train.fit_generator(generator, steps_per_epoch, epochs=epochs, verbose=verbose,
callbacks=callbacks, validation_data=validation_data,
validation_steps=validation_steps, class_weight=class_weight,
max_q_size=max_q_size, workers=workers, pickle_safe=pickle_safe,
initial_epoch=initial_epoch)
self.model_pred.set_weights(self.model_train.get_weights()) # required??
self.model_eval.set_weights(self.model_train.get_weights())
return out
def fit(self, x=None,
y=None,
batch_size=None,
epochs=1,
verbose=1,
callbacks=None,
validation_split=0.0,
validation_data=None,
shuffle=True,
class_weight=None,
sample_weight=None,
initial_epoch=0,
steps_per_epoch=None,
validation_steps=None):
"""
Model training on data.
A major modification concerns the x input of the form:
[input_sequences, label_sequences, inputs_lengths, labels_length]
(in a similar way than for using CTC in tensorflow)
:param: See keras.engine.Model.fit()
:return: A History object
"""
out = self.model_train.fit(x=x, y=y, batch_size=batch_size, epochs=epochs, verbose=verbose,
callbacks=callbacks, validation_split=validation_split, validation_data=validation_data,
shuffle=shuffle, class_weight=class_weight, sample_weight=sample_weight, initial_epoch=initial_epoch,
steps_per_epoch=steps_per_epoch, validation_steps=validation_steps)
self.model_pred.set_weights(self.model_train.get_weights())
self.model_eval.set_weights(self.model_train.get_weights())
return out
def train_on_batch(self, x, y, sample_weight=None, class_weight=None):
""" Runs a single gradient update on a single batch of data.
See Keras.Model for more details.
"""
out = self.model_train.train_on_batch(x, y, sample_weight=sample_weight,
class_weight=class_weight)
self.model_pred.set_weights(self.model_train.get_weights())
self.model_eval.set_weights(self.model_train.get_weights())
return out
def evaluate(self, x=None, batch_size=None, verbose=1, steps=None, metrics=['loss', 'ler', 'ser']):
""" Evaluates the model on a dataset_manager.
:param: See keras.engine.Model.predict()
:return: A History object
CTC evaluation on data yielded batch-by-batch by a Python generator.
Inputs x:
x_input = Input data as a 3D Tensor (batch_size, max_input_len, dim_features)
y = Input data as a 2D Tensor (batch_size, max_label_len)
x_len = 1D array with the length of each data in batch_size
y_len = 1D array with the length of each labeling
metrics = list of metrics that are computed. This is elements among the 3 following metrics:
'loss' : compute the loss function on x
'ler' : compute the label error rate
'ser' : compute the sequence error rate
Outputs: a list containing:
ler_dataset = label error rate for each data (a list)
seq_error = sequence error rate on the dataset_manager
"""
seq_error = 0
x_input = x[0]
x_len = x[2]
y = x[1]
y_len = x[3]
nb_data = x_input.shape[0]
if 'ler' in metrics or 'ser' in metrics:
eval_batch = self.model_eval.predict([x_input, y, x_len, y_len], batch_size=batch_size, verbose=verbose, steps=steps)
if 'ser' in metrics:
seq_error += np.sum([1 for ler_data in eval_batch if ler_data != 0])
seq_error = seq_error / nb_data if nb_data > 0 else -1.
outmetrics = []
if 'loss' in metrics:
outmetrics.append(self.get_loss(x))
if 'ler' in metrics:
outmetrics.append(eval_batch)
if 'ser' in metrics:
outmetrics.append(seq_error)
return outmetrics
def test_on_batch(self, x=None, metrics=['loss', 'ler', 'ser']):
""" Name of a Keras Model function: this relates to evaluate on batch """
return self.evaluate_on_batch(x)
def evaluate_on_batch(self, x=None, metrics=['loss', 'ler', 'ser']):
""" Evaluates the model on a dataset_manager.
:param: See keras.engine.Model.predict_on_batch()
:return: A History object
CTC evaluation on data yielded batch-by-batch by a Python generator.
Inputs x:
x_input = Input data as a 3D Tensor (batch_size, max_input_len, dim_features)
y = Input data as a 2D Tensor (batch_size, max_label_len)
x_len = 1D array with the length of each data in batch_size
y_len = 1D array with the length of each labeling
metrics = list of metrics that are computed. This is elements among the 3 following metrics:
'loss' : compute the loss function on x
'ler' : compute the label error rate
'ser' : compute the sequence error rate
Outputs: a list containing:
ler_dataset = label error rate for each data (a list)
seq_error = sequence error rate on the dataset_manager
"""
seq_error = 0
x_input = x[0]
x_len = x[2]
y = x[1]
y_len = x[3]
nb_data = x_input.shape[0]
if 'ler' in metrics or 'ser' in metrics:
eval_batch = self.model_eval.predict_on_batch([x_input, y, x_len, y_len])
if 'ser' in metrics:
seq_error += np.sum([1 for ler_data in eval_batch if ler_data != 0])
seq_error = seq_error / nb_data if nb_data > 0 else -1.
outmetrics = []
if 'loss' in metrics:
outmetrics.append(self.get_loss(x))
if 'ler' in metrics:
outmetrics.append(eval_batch)
if 'ser' in metrics:
outmetrics.append(seq_error)
return outmetrics
def evaluate_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0, metrics=['ler', 'ser']):
""" Evaluates the model on a data generator.
:param: See keras.engine.Model.fit()
:return: A History object
CTC evaluation on data yielded batch-by-batch by a Python generator.
Inputs:
generator = DataGenerator class that returns:
x = Input data as a 3D Tensor (batch_size, max_input_len, dim_features)
y = Input data as a 2D Tensor (batch_size, max_label_len)
x_len = 1D array with the length of each data in batch_size
y_len = 1D array with the length of each labeling
nb_batchs = number of batchs that are evaluated
metrics = list of metrics that are computed. This is elements among the 3 following metrics:
'loss' : compute the loss function on x
'ler' : compute the label error rate
'ser' : compute the sequence error rate
Warning: if the 'loss' and another metric are requested, make sure that the number of steps allows to evaluate the entire dataset,
even if the data given by the generator will be not the same for all metrics. To make sure, you can only compute 'ler' and 'ser' here
then initialize again the generator and call get_loss_generator.
Outputs: a list containing the metrics given in argument:
loss : the loss on the set
ler : the label error rate for each data (a list)
seq_error : the sequence error rate on the dataset
"""
if 'ler' in metrics or 'ser' in metrics:
ler_dataset = self.model_eval.predict_generator(generator, steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose)
if 'ser' in metrics:
seq_error = float(np.sum([1 for ler_data in ler_dataset if ler_data != 0])) / len(ler_dataset) if len(ler_dataset)>0 else 1.
outmetrics = []
if 'loss' in metrics:
outmetrics.append(self.get_loss_generator(generator, steps))
if 'ler' in metrics:
outmetrics.append(ler_dataset)
if 'ser' in metrics:
outmetrics.append(seq_error)
return outmetrics
def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
# Arguments
x: [Input samples as a Numpy array, Input length as a numpy array]
# Returns
Numpy array(s) of predictions.
"""
batch_size = x[0].shape[0]
return self.predict(x, batch_size=batch_size)
def predict_generator(self, generator, steps,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
decode_func=None):
"""Generates predictions for the input samples from a data generator.
The generator should return the same kind of data as accepted by
`predict_on_batch`.
generator = DataGenerator class that returns:
x = Input data as a 3D Tensor (batch_size, max_input_len, dim_features)
y = Input data as a 2D Tensor (batch_size, max_label_len)
x_len = 1D array with the length of each data in batch_size
y_len = 1D array with the length of each labeling
# Arguments
generator: Generator yielding batches of input samples
or an instance of Sequence (keras.utils.Sequence)
object in order to avoid duplicate data
when using multiprocessing.
steps: Total number of steps (batches of samples)
to yield from `generator` before stopping.
max_queue_size: Maximum size for the generator queue.
workers: Maximum number of processes to spin up
when using process based threading
use_multiprocessing: If `True`, use process based threading.
Note that because
this implementation relies on multiprocessing,
you should not pass
non picklable arguments to the generator
as they can't be passed
easily to children processes.
verbose: verbosity mode, 0 or 1.
decode_func: a function for decoding a list of predicted sequences (using self.charset)
# Returns
A tuple containing:
A numpy array(s) of predictions.
A numpy array(s) of ground truth.
# Raises
ValueError: In case the generator yields
data in an invalid format.
"""
self.model_pred._make_predict_function()
steps_done = 0
wait_time = 0.01
all_outs = []
all_lab = []
is_sequence = isinstance(generator, Sequence)
if not is_sequence and use_multiprocessing and workers > 1:
warnings.warn(
UserWarning('Using a generator with `use_multiprocessing=True`'
' and multiple workers may duplicate your data.'
' Please consider using the`keras.utils.Sequence'
' class.'))
enqueuer = None
try:
if is_sequence:
enqueuer = OrderedEnqueuer(generator,
use_multiprocessing=use_multiprocessing)
else:
enqueuer = GeneratorEnqueuer(generator,
use_multiprocessing=use_multiprocessing,
wait_time=wait_time)
enqueuer.start(workers=workers, max_queue_size=max_queue_size)
output_generator = enqueuer.get()
if verbose == 1:
progbar = Progbar(target=steps)
while steps_done < steps:
generator_output = next(output_generator)
if isinstance(generator_output, tuple):
# Compatibility with the generators
# used for training.
if len(generator_output) == 2:
x, _ = generator_output
elif len(generator_output) == 3:
x, _, _ = generator_output
else:
raise ValueError('Output of generator should be '
'a tuple `(x, y, sample_weight)` '
'or `(x, y)`. Found: ' +
str(generator_output))
else:
# Assumes a generator that only
# yields inputs (not targets and sample weights).
x = generator_output
[x_input, y, x_length, y_length] = x
outs = self.predict_on_batch([x_input, x_length])
if not isinstance(outs, list):
outs = [outs]
if not all_outs:
for out in outs:
all_outs.append([])
all_lab.append([])
for i, out in enumerate(outs):
all_outs[i].append([val_out for val_out in out if val_out!=-1])
if isinstance(y_length[i], list):
all_lab[i].append(y[i][:y_length[i][0]])
elif isinstance(y_length[i], int):
all_lab[i].append(y[i][:y_length[i]])
elif isinstance(y_length[i], float):
all_lab[i].append(y[i][:int(y_length[i])])
else:
all_lab[i].append(y[i])
steps_done += 1
if verbose == 1:
progbar.update(steps_done)
finally:
if enqueuer is not None:
enqueuer.stop()
batch_size = len(all_outs)
nb_data = len(all_outs[0])
pred_out = []
lab_out = []
for i in range(nb_data):
pred_out += [all_outs[b][i] for b in range(batch_size)]
lab_out += [all_lab[b][i] for b in range(batch_size)]
if decode_func is not None: # convert model prediction (a label between 0 to nb_labels to an original label sequence)
pred_out = decode_func(pred_out, self.charset)
lab_out = decode_func(lab_out, self.charset)
return pred_out, lab_out
def predict(self, x, batch_size=None, verbose=0, steps=None, max_len=None, max_value=999):
"""
The same function as in the Keras Model but with a different function predict_loop for dealing with variable length predictions
Except that x = [x_features, x_len]
Generates output predictions for the input samples.
Computation is done in batches.
# Arguments
x: The input data, as a Numpy array
(or list of Numpy arrays if the model has multiple outputs).
batch_size: Integer. If unspecified, it will default to 32.
verbose: Verbosity mode, 0 or 1.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`.
# Returns
Numpy array(s) of predictions.
# Raises
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
[x_inputs, x_len] = x
if max_len is None:
max_len = np.max(x_len)
# Backwards compatibility.
if batch_size is None and steps is None:
batch_size = 32
if x is None and steps is None:
raise ValueError('If predicting from data tensors, '
'you should specify the `steps` '
'argument.')
# Validate user data.
x = _standardize_input_data(x, self.model_pred._feed_input_names,
self.model_pred._feed_input_shapes,
check_batch_axis=False)
if self.model_pred.stateful:
if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
raise ValueError('In a stateful network, '
'you should only pass inputs with '
'a number of samples that can be '
'divided by the batch size. Found: ' +
str(x[0].shape[0]) + ' samples. '
'Batch size: ' + str(batch_size) + '.')
# Prepare inputs, delegate logic to `_predict_loop`.
if self.model_pred.uses_learning_phase and not isinstance(K.learning_phase(), int):
ins = x + [0.]
else:
ins = x
self.model_pred._make_predict_function()
f = self.model_pred.predict_function
out = self._predict_loop(f, ins, batch_size=batch_size, max_value=max_value,
verbose=verbose, steps=steps, max_len=max_len)
out_decode = [dec_data[:list(dec_data).index(max_value)] if max_value in dec_data else dec_data for i,dec_data in enumerate(out)]
return out_decode
def _predict_loop(self, f, ins, max_len=100, max_value=999, batch_size=32, verbose=0, steps=None):
"""Abstract method to loop over some data in batches.
Keras function that has been modified.
# Arguments
f: Keras function returning a list of tensors.
ins: list of tensors to be fed to `f`.
batch_size: integer batch size.
verbose: verbosity mode.
steps: Total number of steps (batches of samples)
before declaring `_predict_loop` finished.
Ignored with the default value of `None`.
# Returns
Array of predictions (if the model has a single output)
or list of arrays of predictions
(if the model has multiple outputs).
"""
num_samples = self.model_pred._check_num_samples(ins, batch_size,
steps,
'steps')
if steps is not None:
# Step-based predictions.
# Since we do not know how many samples
# we will see, we cannot pre-allocate
# the returned Numpy arrays.
# Instead, we store one array per batch seen
# and concatenate them upon returning.
unconcatenated_outs = []
for step in range(steps):
batch_outs = f(ins)
if not isinstance(batch_outs, list):
batch_outs = [batch_outs]
if step == 0:
for batch_out in batch_outs:
unconcatenated_outs.append([])
for i, batch_out in enumerate(batch_outs):
unconcatenated_outs[i].append(batch_out)
if len(unconcatenated_outs) == 1:
return np.concatenate(unconcatenated_outs[0], axis=0)
return [np.concatenate(unconcatenated_outs[i], axis=0)
for i in range(len(unconcatenated_outs))]
else:
# Sample-based predictions.
outs = []
batches = _make_batches(num_samples, batch_size)
index_array = np.arange(num_samples)
for batch_index, (batch_start, batch_end) in enumerate(batches):
batch_ids = index_array[batch_start:batch_end]
if ins and isinstance(ins[-1], float):
# Do not slice the training phase flag.
ins_batch = _slice_arrays(ins[:-1], batch_ids) + [ins[-1]]
else:
ins_batch = _slice_arrays(ins, batch_ids)
batch_outs = f(ins_batch)
if not isinstance(batch_outs, list):
batch_outs = [batch_outs]
if batch_index == 0:
# Pre-allocate the results arrays.
for batch_out in batch_outs:
shape = (num_samples,max_len)
outs.append(np.zeros(shape, dtype=batch_out.dtype))
for i, batch_out in enumerate(batch_outs):
outs[i][batch_start:batch_end] = sequence.pad_sequences(batch_out, value=float(max_value), maxlen=max_len,
dtype=batch_out.dtype, padding="post")
if len(outs) == 1:
return outs[0]
return outs
@staticmethod
def ctc_loss_lambda_func(args):
"""
Function for computing the ctc loss (can be put in a Lambda layer)
:param args:
y_pred, labels, input_length, label_length
:return: CTC loss
"""
y_pred, labels, input_length, label_length = args
return K.ctc_batch_cost(labels, y_pred, input_length, label_length)#, ignore_longer_outputs_than_inputs=True)
@staticmethod
def ctc_complete_decoding_lambda_func(args, **arguments):
"""
Complete CTC decoding using Keras (function K.ctc_decode)
:param args:
y_pred, input_length
:param arguments:
greedy, beam_width, top_paths
:return:
K.ctc_decode with dtype='float32'
"""
#import tensorflow as tf # Require for loading a model saved
y_pred, input_length = args
my_params = arguments
assert (K.backend() == 'tensorflow')
return K.cast(K.ctc_decode(y_pred, tf.squeeze(input_length), greedy=my_params['greedy'], beam_width=my_params['beam_width'], top_paths=my_params['top_paths'])[0][0], dtype='float32')
@staticmethod
def ctc_complete_analysis_lambda_func(args, **arguments):
"""
Complete CTC analysis using Keras and tensorflow
WARNING : tf is required
:param args:
y_pred, labels, input_length, label_len
:param arguments:
greedy, beam_width, top_paths
:return:
ler = label error rate
"""
#import tensorflow as tf # Require for loading a model saved
y_pred, labels, input_length, label_len = args
my_params = arguments
assert (K.backend() == 'tensorflow')
batch = tf.log(tf.transpose(y_pred, perm=[1, 0, 2]) + 1e-8)
input_length = tf.to_int32(tf.squeeze(input_length))
greedy = my_params['greedy']
beam_width = my_params['beam_width']
top_paths = my_params['top_paths']
if greedy:
(decoded, log_prob) = ctc.ctc_greedy_decoder(
inputs=batch,
sequence_length=input_length)
else:
(decoded, log_prob) = ctc.ctc_beam_search_decoder(
inputs=batch, sequence_length=input_length,
beam_width=beam_width, top_paths=top_paths)
cast_decoded = tf.cast(decoded[0], tf.float32)
sparse_y = K.ctc_label_dense_to_sparse(labels, tf.cast(tf.squeeze(label_len), tf.int32))
ed_tensor = tf_edit_distance(cast_decoded, sparse_y, norm=True)
ler_per_seq = Kreshape_To1D(ed_tensor)
return K.cast(ler_per_seq, dtype='float32')
def save_model(self, path_dir, charset=None):
""" Save a model in path_dir
save model_train, model_pred and model_eval in json
save inputs and outputs in json
save model CTC parameters in a pickle
:param path_dir: directory where the model architecture will be saved
:param charset: set of labels (useful to keep the label order)
"""
model_json = self.model_train.to_json()
with open(path_dir + "/model_train.json", "w") as json_file:
json_file.write(model_json)
model_json = self.model_pred.to_json()
with open(path_dir + "/model_pred.json", "w") as json_file:
json_file.write(model_json)
model_json = self.model_eval.to_json()
with open(path_dir + "/model_eval.json", "w") as json_file:
json_file.write(model_json)
model_json = self.model_init.to_json()
with open(path_dir + "/model_init.json", "w") as json_file:
json_file.write(model_json)
param = {'greedy': self.greedy, 'beam_width': self.beam_width, 'top_paths': self.top_paths, 'charset': self.charset}
output = open(path_dir + "/model_param.pkl", 'wb')
p = pickle.Pickler(output)
p.dump(param)
output.close()
def load_model(self, path_dir, optimizer, file_weights=None):
""" Load a model in path_dir
load model_train, model_pred and model_eval from json
load inputs and outputs from json
load model CTC parameters from a pickle
:param path_dir: directory where the model is saved
:param optimizer: The optimizer used during training
"""
json_file = open(path_dir + '/model_train.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
self.model_train = model_from_json(loaded_model_json)
json_file = open(path_dir + '/model_pred.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
self.model_pred = model_from_json(loaded_model_json, custom_objects={"tf": tf})
json_file = open(path_dir + '/model_eval.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
self.model_eval = model_from_json(loaded_model_json, custom_objects={"tf": tf, "ctc": ctc,
"tf_edit_distance": tf_edit_distance,
"Kreshape_To1D": Kreshape_To1D})
json_file = open(path_dir + '/model_init.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
self.model_init = model_from_json(loaded_model_json, custom_objects={"tf": tf})
self.inputs = self.model_init.inputs
self.outputs = self.model_init.outputs
input = open(path_dir + "/model_param.pkl", 'rb')
p = pickle.Unpickler(input)
param = p.load()
input.close()
self.greedy = param['greedy'] if 'greedy' in param.keys() else self.greedy
self.beam_width = param['beam_width'] if 'beam_width' in param.keys() else self.beam_width
self.top_paths = param['top_paths'] if 'top_paths' in param.keys() else self.top_paths
self.charset = param['charset'] if 'charset' in param.keys() else self.charset
self.compile(optimizer)
if file_weights is not None:
if os.path.exists(file_weights):
self.model_train.load_weights(file_weights)
self.model_pred.set_weights(self.model_train.get_weights())
self.model_eval.set_weights(self.model_train.get_weights())
elif os.path.exists(path_dir + file_weights):
self.model_train.load_weights(path_dir + file_weights)
self.model_pred.set_weights(self.model_train.get_weights())
self.model_eval.set_weights(self.model_train.get_weights())
def _standardize_input_data(data, names, shapes=None,
check_batch_axis=True,
exception_prefix=''):
"""Normalizes inputs and targets provided by users.
Users may pass data as a list of arrays, dictionary of arrays,
or as a single array. We normalize this to an ordered list of
arrays (same order as `names`), while checking that the provided
arrays have shapes that match the network's expectations.