-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassifiers.py
More file actions
2617 lines (2517 loc) · 119 KB
/
Copy pathclassifiers.py
File metadata and controls
2617 lines (2517 loc) · 119 KB
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
'''
Implementation of Classifier Training, partly described inside Fanello et al.
'''
import sys
import signal
import errno
import glob
import numpy as np
import class_objects as co
import action_recognition_alg as ara
import cv2
import os.path
import cPickle as pickle
import logging
import yaml
import time
from OptGridSearchCV import optGridSearchCV
# pylint: disable=no-member,R0902,too-many-public-methods,too-many-arguments
# pylint: disable=too-many-locals, too-many-branches, too-many-statements
def timeit(func):
'''
Decorator to time extraction
'''
def wrapper(self, *arg, **kw):
t1 = time.time()
res = func(self, *arg, **kw)
t2 = time.time()
self.time.append(t2 - t1)
del self.time[:-5000]
return res
return wrapper
class Classifier(object):
'''
Class to hold all Classifier specific methods.
<descriptors>:['pca','ghog','3dhof']
<action_type>:True if no buffers are used
<sparsecoding_level> is True if sparse coding is used
Classifier Parameters, for example <AdaBoost_n_estimators> or
<RDF_n_estimators> or <kernel> can be
a list, which will be reduced using optimized grid search with cross
validation.
'''
def __init__(self, log_lev='INFO',
visualize=False, masks_needed=True,
buffer_size=co.CONST['buffer_size'],
sparse_dim_rat=co.CONST['sparse_dim_rat'],
descriptors='',
ptpca=False,
ptpca_components=None,
action_type='Dynamic',
classifiers_used='SVM', num_of_cores=4, name='',
svm_c=None,
AdaBoost_n_estimators=None,
RDF_n_estimators=None,
add_info=None,
sparsecoding_level=None,
kernel=None,
save_all_steps=False,
post_scores_processing_method=None,
hardcore=False,
for_app=False):
'''
sparsecoding_level = [Buffer, Features, None]
'''
if not os.path.isdir(co.CONST['AppData']):
os.makedirs(co.CONST['AppData'])
self.app_dir = co.CONST['AppData']
self.for_app = for_app
self.time = []
self.classifiers_ids = None
self.test_ind = None
# General configuration
if not isinstance(descriptors, list):
descriptors = [descriptors]
descriptors = sorted(descriptors)
###
features_params = {}
coders_params = {}
for descriptor in descriptors:
features_params[descriptor] = {}
features_params[descriptor]['params'] = {attrib.replace(descriptor, ''):
co.CONST[attrib] for
attrib in co.CONST if
attrib.startswith(descriptor)}
features_params[descriptor]['sparsecoded'] = sparsecoding_level
features_params[descriptor]['action_type'] = action_type
coders_params[descriptor] = {}
if not sparsecoding_level:
features_params[descriptor]['sparse_params'] = None
else:
features_params[descriptor]['sparse_params'] = {
attrib.replace('sparse', ''):
co.CONST[attrib] for
attrib in co.CONST if
attrib.startswith('sparse')}
coders_params[descriptor] = {
attrib.replace('sparse', ''):
co.CONST[attrib] for
attrib in co.CONST if
attrib.startswith('sparse') and
'fss' not in attrib}
self.test_name = None
self.kernel = kernel
self.svm_c = svm_c
self.RDF_n_estimators = RDF_n_estimators
self.AdaBoost_n_estimators = AdaBoost_n_estimators
self.sparse_dim_rat = sparse_dim_rat
if 'SVM' in classifiers_used and kernel is None:
self.kernel = 'linear'
if 'SVM' in classifiers_used:
if svm_c is None:
self.svm_c = co.CONST['SVM_C']
if post_scores_processing_method == 'CProb':
LOG.warning('Invalid post_scores_processing_method for SVM')
if hardcore:
raise Exception
else:
LOG.warning('Changing method to CSTD')
post_scores_processing_method = 'CSTD'
if 'RDF' in classifiers_used or 'AdaBoost' in classifiers_used:
if svm_c is not None:
LOG.warning(
'svm_c is not None for RDF or AdaBoost experimentation')
if hardcore:
raise Exception
if post_scores_processing_method is None:
if 'RDF' in classifiers_used or 'AdaBoost' in classifiers_used:
post_scores_processing_method = 'CProb'
else:
post_scores_processing_method = 'CSTD'
classifier_params = {}
if 'RDF' in classifiers_used and RDF_n_estimators is None:
self.RDF_n_estimators = co.CONST['RDF_trees']
if 'AdaBoost' in classifiers_used and AdaBoost_n_estimators is None:
self.AdaBoost_n_estimators = co.CONST['AdaBoost_Estimators']
if 'SVM' in classifiers_used:
classifier_params['SVM_kernel'] = self.kernel
classifier_params['SVM_C'] = self.svm_c
if 'RDF' in classifiers_used:
classifier_params['RDF_n_estimators'] = self.RDF_n_estimators
if 'AdaBoost' in classifiers_used:
classifier_params['AdaBoost_n_estimators'] = self.AdaBoost_n_estimators
if action_type != 'Passive':
dynamic_params = {'buffer_size': buffer_size,
'buffer_confidence_tol': co.CONST['buffer_confidence_tol'],
'filter_window_size':
co.CONST['STD_big_filt_window']}
else:
dynamic_params = {'buffer_size': 1}
if ptpca and ptpca_components is None:
ptpca_components = co.CONST['PTPCA_components']
ptpca_params = {'PTPCA_components': ptpca_components}
for descriptor in descriptors:
features_params[descriptor]['dynamic_params'] = dynamic_params
if sparsecoding_level:
if not isinstance(sparse_dim_rat, list):
sparse_dim_rat = [sparse_dim_rat] * len(descriptors)
if len(list(sparse_dim_rat)) != len(descriptors):
raise Exception('<sparse_dim_rat> should be either an integer/None or' +
' a list with same length with <descriptors>')
sparse_params = dict(zip(descriptors, sparse_dim_rat))
sparse_params['fss_max_iter'] = co.CONST['sparse_fss_max_iter']
else:
sparse_params = None
testing_params = {'online': None}
testing_params['post_scores_processing_method'] = \
post_scores_processing_method
fil = os.path.join(co.CONST['rosbag_location'],
'gestures_type.csv')
self.passive_actions = None
self.dynamic_actions = None
if os.path.exists(fil):
with open(fil, 'r') as inp:
for line in inp:
if line.split(':')[0] == 'Passive':
self.passive_actions = line.split(
':')[1].rstrip('\n').split(',')
elif line.split(':')[0] == 'Dynamic':
self.dynamic_actions = line.split(
':')[1].rstrip('\n').split(',')
action_params = {'Passive': self.passive_actions,
'Dynamic': self.dynamic_actions}
LOG.debug('Extracting: ' + str(descriptors))
self.parameters = {'classifier': classifiers_used,
'descriptors': descriptors,
'features_params': features_params,
'coders_params': coders_params,
'dynamic_params': dynamic_params,
'classifier_params': classifier_params,
'sparse_params': sparse_params,
'action_type': action_type,
'sparsecoded': sparsecoding_level,
'testing': False,
'testing_params': testing_params,
'actions_params': action_params,
'PTPCA': ptpca,
'PTPCA_params': ptpca_params}
self.training_parameters = {k: self.parameters[k] for k in
('classifier', 'descriptors',
'features_params',
'dynamic_params',
'classifier_params',
'sparse_params',
'action_type',
'sparsecoded',
'PTPCA',
'PTPCA_params') if k in
self.parameters}
self.descriptors = descriptors
self.add_info = add_info
self.log_lev = log_lev
self.visualize = visualize
self.buffer_size = buffer_size
self.masks_needed = masks_needed
self.action_type = action_type
self.classifiers_used = classifiers_used
self.num_of_cores = num_of_cores
self.name = name
self.ptpca = ptpca
self.action_recog = ara.ActionRecognition(
self.parameters,
log_lev=log_lev)
if not self.for_app:
self.available_tests = sorted(os.listdir(co.CONST['test_save_path']))
else:
self.available_tests = []
self.update_experiment_info()
if 'SVM' in self.classifiers_used:
from sklearn.svm import LinearSVC
self.classifier_type = LinearSVC(
class_weight='balanced', C=self.svm_c,
multi_class='ovr',
dual=False)
elif 'RDF' in self.classifiers_used:
from sklearn.ensemble import RandomForestClassifier
self.classifier_type =\
RandomForestClassifier(self.RDF_n_estimators)
elif 'AdaBoost' in self.classifiers_used:
from sklearn.ensemble import AdaBoostClassifier
self.classifier_type =\
AdaBoostClassifier(n_estimators=self.AdaBoost_n_estimators)
self.unified_classifier = None
if sparsecoding_level:
if not(sparsecoding_level == 'Features' or sparsecoding_level == 'Buffer'):
raise Exception('Invalid sparsecoding_level, its value shoud be '
+ 'None/False/Buffer/Features')
self.sparsecoded = sparsecoding_level
self.decide = None
# Training variables
self.training_data = None
self.train_ground_truth = None # is loaded from memory after training
self.train_classes = None # is loaded from memory after training
# Testing general variables
self.accuracy = None
self.f1_scores = None
self.confusion_matrix = None
self.scores_savepath = None
self.scores_std = []
self.scores_std_mean = []
self.scores = None
self.scores_filter_shape = None
self.std_big_filter_shape = None
self.std_small_filter_shape = None
self.recognized_classes = []
self.crossings = None
self.testname = ''
self.save_fold = None
self.online = False
# Testing offline variables
self.testdataname = ''
self.test_instances = None
# Testing online variables
self.count_prev = None
self.buffer_exists = None
self.scores_exist = None
self.img_count = -1
self._buffer = []
self.scores_running_mean_vec = []
self.big_std_running_mean_vec = []
self.small_std_running_mean_vec = []
self.saved_buffers_scores = []
self.new_action_starts_count = 0
self.test_ground_truth = None
self.mean_from = -1
self.on_action = False
self.act_inds = []
self.max_filtered_score = 0
self.less_filtered_scores_std = None
self.high_filtered_scores_std = None
self.classifier_folder = None
self.testing_initialized = False
self.classifiers_list = {}
self.classifier_savename = 'trained_'
self.classifier_savename += self.full_info.replace(' ', '_').lower()
try:
[self.unified_classifier,
info] = co.file_oper.load_labeled_data(
['Classifier'] + self.classifier_id)
co.file_oper.save_labeled_data(['Classifier'],
[self.unified_classifier,
self.training_parameters],
name=self.app_dir)
if isinstance(info, tuple):
self.training_params = info[0]
self.additional_params = info[1:]
else:
self.training_params = info
self.loaded_classifier = True
LOG.info('Loaded Classifier')
except TypeError:
if self.for_app:
[self.unified_classifier,
info] = co.file_oper.load_labeled_data(
['Classifier'],
name=self.app_dir)
self.loaded_classifier = True
else:
self.loaded_classifier = False
LOG.info('Classifier not Loaded')
self.load_tests()
try:
self.classifier_folder = str(self.classifiers_list[
self.classifier_savename])
except KeyError:
self.classifier_folder = str(len(self.classifiers_list))
self.coders_to_train = []
# parameters bound variables
self.frames_preproc = ara.FramesPreprocessing(self.parameters)
available_descriptors =\
ara.Actions(self.parameters).available_descriptors
try:
self.features_extractors = [available_descriptors[nam](
self.parameters, self.frames_preproc)
for nam in self.parameters['descriptors']]
self.buffer_operators = [
ara.BufferOperations(self.parameters)
for nam in self.parameters['descriptors']]
if self.sparsecoded:
[self.action_recog.
actions.load_sparse_coder(ind) for ind in range(
len(self.parameters['descriptors']))]
except BaseException: pass
def load_tests(self, reset=True):
if reset:
self.testdata = [None] * len(self.available_tests)
self.fscores = [None] * len(self.available_tests)
self.accuracies = [None] * len(self.available_tests)
self.results = [None] * len(self.available_tests)
self.conf_mats = [None] * len(self.available_tests)
self.test_times = [None] * len(self.available_tests)
for count, test in enumerate(self.available_tests):
if (self.testdata[count] is None or
self.testdata[count]['Accuracy'] is None):
self.testdata[count] = co.file_oper.load_labeled_data(
['Testing'] + self.tests_ids[count])
if (self.testdata[count] is not None and
self.testdata[count]['Accuracy'] is not None):
self.accuracies[count] = self.testdata[count]['Accuracy']
self.fscores[count] = self.testdata[count]['FScores']
self.results[count] = self.testdata[count]['Results']
self.conf_mats[count] = self.testdata[count]['ConfMat']
self.test_times[count] = self.testdata[count]['TestTime']
try:
self.partial_accuracies[count] = self.testdata[count][
'PartialAccuracies']
except BaseException: pass
else:
self.testdata[count] = {}
self.testdata[count]['Accuracy'] = {}
self.testdata[count]['FScores'] = {}
self.testdata[count]['Results'] = {}
self.testdata[count]['ConfMat'] = {}
self.testdata[count]['TestTime'] = {}
self.testdata[count]['Labels'] = {}
try:
self.testdata[count]['PartialAccuracies'] = {}
except BaseException: pass
def update_experiment_info(self):
if self.parameters['action_type'] == 'Passive':
info = 'passive '
else:
info = 'dynamic '
info = info + self.name + ' ' + self.classifiers_used + ' '
info += 'using'
if self.parameters['sparsecoded']:
info += ' sparsecoded'
for feature in self.parameters['descriptors']:
info += ' ' + feature
info += ' descriptors '
if 'SVM' in self.parameters['classifier']:
info += 'with ' + self.parameters[
'classifier_params']['SVM_kernel'] + ' kernel'
elif 'RDF' in self.parameters['classifier']:
info += ('with ' + str(self.parameters['classifier_params'][
'RDF_n_estimators']) + ' estimators')
elif 'AdaBoost' in self.parameters['classifier']:
info += ('with ' + str(self.parameters['classifier_params'][
'AdaBoost_n_estimators']) + ' estimators')
if self.parameters['action_type'] == 'Dynamic':
info += ' with buffer size ' + str(self.buffer_size)
if self.parameters['sparsecoded']:
info += ' with sparsecoding by ratio of ' + \
str(self.sparse_dim_rat)
if self.ptpca:
info += (' with ' +
str(self.parameters['PTPCA_params']['PTPCA_components']) +
' post-time-pca components')
self.full_info = info.title()
if self.add_info:
info += self.add_info
self.classifier_savename = 'trained_'
self.classifier_savename += self.full_info.replace(' ', '_').lower()
self.update_classifier_id()
self.update_tests_ids()
def update_classifier_id(self):
self.features_file_id = []
self.features_id = []
for count in range(len(self.parameters['descriptors'])):
_id, file_id = self.action_recog.actions.retrieve_descriptor_possible_ids(count,
assume_existence=True)
self.features_id.append(_id)
self.features_file_id.append(file_id)
self.classifier_id = [co.dict_oper.create_sorted_dict_view(
{'Classifier': str(self.classifiers_used)}),
co.dict_oper.create_sorted_dict_view(
{'ClassifierParams': str(co.dict_oper.create_sorted_dict_view(
self.parameters['classifier_params']))}),
co.dict_oper.create_sorted_dict_view(
{'ActionsType': str(self.action_type)}),
co.dict_oper.create_sorted_dict_view(
{'FeaturesParams': str(self.features_file_id)})]
def update_tests_ids(self):
self.tests_ids = []
for count, test in enumerate(self.available_tests):
self.tests_ids.append([co.dict_oper.create_sorted_dict_view({'Test': str(test)}),
co.dict_oper.create_sorted_dict_view(
{'TestingParams': str(co.dict_oper.create_sorted_dict_view(
self.parameters['testing_params']))})]
+ [self.classifier_id])
def initialize_classifier(self, classifier):
'''
Add type to classifier and set methods
'''
self.unified_classifier = classifier
if 'SVM' in self.classifiers_used:
self.unified_classifier.decide = self.unified_classifier.decision_function
self.unified_classifier.predict = self.unified_classifier.predict
elif 'RDF' in self.classifiers_used or 'AdaBoost' in self.classifiers_used:
self.unified_classifier.decide = self.unified_classifier.predict_proba
self.unified_classifier.predict = self.unified_classifier.predict
co.file_oper.save_labeled_data(['Classifier'] + self.classifier_id,
[self.unified_classifier,
self.training_parameters])
co.file_oper.save_labeled_data(['Classifier'],
[self.unified_classifier,
self.training_parameters],
name=self.app_dir)
def reset_offline_test(self):
'''
Reset offline testing variables
'''
# Testing general variables
self.scores_std = []
self.scores_std_mean = []
self.scores = None
self.recognized_classes = []
self.crossings = None
self.save_fold = None
self.testing_initialized = True
# Testing offline variables
def reset_online_test(self):
'''
Reset online testing variables
'''
# Testing general variables
self.scores_std = []
self.scores_std_mean = []
self.scores = []
self.recognized_classes = []
self.crossings = []
self.save_fold = None
# Testing online variables
self.count_prev = None
self.buffer_exists = []
self.scores_exist = []
self.img_count = -1
self._buffer = []
self.scores_running_mean_vec = []
self.big_std_running_mean_vec = []
self.small_std_running_mean_vec = []
self.saved_buffers_scores = []
self.new_action_starts_count = 0
self.test_ground_truth = None
self.mean_from = -1
self.on_action = False
self.act_inds = []
self.max_filtered_score = 0
self.less_filtered_scores_std = None
self.high_filtered_scores_std = None
self.testing_initialized = True
def add_train_classes(self, training_datapath):
'''
Set the training classes of the classifier
'''
try:
self.train_classes = [name for name in os.listdir(training_datapath)
if os.path.isdir(os.path.join(training_datapath, name))][::-1]
except:
if self.for_app:
with open(os.path.join(self.app_dir,
'train_classes'),'r') as inp:
self.train_classes = pickle.load(inp)
else:
raise
self.all_actions = ['Undefined'] + self.train_classes
# Compare actions in memory with actions in file 'gestures_type.csv'
if self.passive_actions is not None:
passive_actions = [clas for clas in
(self.passive_actions) if clas
in self.train_classes]
if self.dynamic_actions is not None:
dynamic_actions = [clas for clas in
(self.dynamic_actions) if clas
in self.train_classes]
if (self.dynamic_actions is not None and
self.passive_actions is not None):
if 'Sync' in self.classifiers_used:
self.train_classes = {'Passive': passive_actions,
'Dynamic': dynamic_actions}
else:
classes = []
if self.action_type == 'Dynamic' or self.action_type == 'All':
classes += dynamic_actions
if self.action_type == 'Passive' or self.action_type == 'All':
classes += passive_actions
self.train_classes = classes
with open(os.path.join(self.app_dir,
'train_classes'),'w') as out:
pickle.dump(self.train_classes, out)
def run_training(self, coders_retrain=False,
classifiers_retrain=False,
training_datapath=None, classifier_savename=None,
num_of_cores=4, classifier_save=True,
max_act_samples=None,
min_dict_iterations=5,
visualize_feat=False, just_sparse=False,
init_sc_traindata_num=200,
train_all=False):
'''
<Arguments>
For coders training:
Do not train coders if coder already exists or <coders_retrain>
is False. <min_dict_iterations> denote the minimum training iterations to
take place after the whole data has been processed from the trainer
of the coder.<init_dict_traindata_num> denotes how many samples
will be used in the first iteration of the sparse coder training
For svm training:
Train ClassifierS with <num_of_cores>.
Save them if <classifier_save> is True to <classifiers_savepath>. Do not train
if <classifiers_savepath> already exists and <classifiers_retrain> is False.
'''
self.train_all = train_all
self.parameters['testing'] = False
LOG.info(self.full_info + ':')
if classifier_savename is not None:
self.classifier_savename = classifier_savename
if training_datapath is None:
training_datapath = co.CONST['actions_path']
self.add_train_classes(training_datapath)
if self.unified_classifier is None:
LOG.info('Missing trained classifier:' +
self.full_info)
LOG.info('Classifier will be retrained')
classifiers_retrain = True
else:
if not self.sparsecoded:
return
self.prepare_training_data(training_datapath, max_act_samples,
visualize_feat=visualize_feat)
if just_sparse:
return
if self.sparsecoded and self.coders_to_train and classifiers_retrain:
# Enters only if coders were not initially trained or had to be
# retrained. Otherwise, sparse descriptors are computed when
#<Action.add_features> is called
LOG.info('Trained' + str([self.parameters['descriptors'][coder] for coder in
self.coders_to_train]))
LOG.info('Making Sparse Features..')
self.action_recog = ara.ActionRecognition(
self.parameters,
log_lev=self.log_lev,
feat_filename=os.path.join(co.CONST['feat_save_path'],
'saved'))
self.prepare_training_data(training_datapath, max_act_samples,
visualize_feat=visualize_feat)
self.process_training(num_of_cores, classifiers_retrain,
self.classifier_savename, classifier_save)
def prepare_training_data(self, path=None, max_act_samples=None,
visualize_feat=False):
'''
Read actions from the <path> and name them according to their parent
folder name
'''
LOG.info('Adding actions..')
while True:
self.training_data = []
self.training_samples_inds = []
for act_count, action in enumerate(self.train_classes):
LOG.info('Action:' + action)
descriptors, samples_indices, mean_depths, _, trained_coders, _ = self.add_action(name=action,
data=os.path.join(
path, action),
use_dexter=False,
action_type=self.action_type,
max_act_samples=max_act_samples)
if not(self.sparsecoded and None in trained_coders):
descriptors = np.hstack(tuple(descriptors))
fmask = np.prod(np.isfinite(
descriptors), axis=1).astype(bool)
descriptors = descriptors[fmask]
LOG.info('Action \'' + action + '\' has ' +
'descriptors of shape ' + str(descriptors.shape))
self.training_data.append(descriptors)
self.training_samples_inds.append(
np.array(samples_indices)[fmask])
else:
self.training_samples_inds = []
self.training_data = []
self.train_ground_truth = []
if self.training_data:
if self.action_type == 'Dynamic':
self.training_data = co.preproc_oper.equalize_samples(
samples=self.training_data,
utterance_indices=self.training_samples_inds,
mode='random')
self.train_ground_truth = []
for act_count, clas in enumerate(self.training_data):
self.train_ground_truth += clas.shape[0] * [act_count]
self.training_data = np.vstack((self.training_data))
if None in trained_coders and self.sparsecoded:
self.action_recog.actions.train_sparse_dictionary()
else:
break
finite_samples = np.prod(
np.isfinite(
self.training_data),
axis=1).astype(bool)
self.train_ground_truth = np.array(
self.train_ground_truth)[finite_samples]
self.training_data = self.training_data[finite_samples, :]
LOG.info('Total Training Data has shape:'
+ str(self.training_data.shape))
def process_training(self, num_of_cores=4, retrain=False,
savepath=None, save=True):
'''
Train (or load trained) Classifiers with number of cores num_of_cores, with buffer size (stride
is 1) <self.buffer_size>. If <retrain> is True, Classifiers are retrained, even if
<save_path> exists.
'''
loaded = 0
if save and savepath is None:
raise Exception('savepath needed')
if retrain or self.unified_classifier is None:
if retrain and self.unified_classifier is not None:
LOG.info('retrain switch is True, so the Classifier ' +
'is retrained')
classifier_params = {elem.replace(self.classifiers_used + '_', ''):
self.parameters['classifier_params'][elem]
for elem in
self.parameters['classifier_params']
if elem.startswith(self.classifiers_used)}
if any([isinstance(classifier_params[elem], list)
for elem in classifier_params]):
grid_search_params = classifier_params.copy()
from sklearn.multiclass import OneVsRestClassifier
if isinstance(self.classifier_type, OneVsRestClassifier):
grid_search_params = {('estimator__' + key): classifier_params[key]
for key in classifier_params}
grid_search_params = {key: (grid_search_params[key] if
isinstance(
grid_search_params[key], list)
else [
grid_search_params[key]]) for key in
classifier_params}
best_params, best_scores, best_estimators = optGridSearchCV(
self.classifier_type, self.training_data,
self.train_ground_truth, grid_search_params, n_jobs=4,
fold_num=3)
best_params = best_params[-1]
best_scores = best_scores[-1]
best_estimator = best_estimators[-1]
if isinstance(self.classifier_type, OneVsRestClassifier):
best_params = {key.replace('estimator__', ''):
classifier_params[
key.replace('estimator__', '')]
for key in best_params}
classifier_params = {self.classifiers_used + '_' + key: best_params[key] for key
in best_params}
self.parameters['classifier_params'].update(classifier_params)
self.training_parameters['classifier_params'].update(
classifier_params)
self.classifier_type = best_estimator
self.update_experiment_info()
savepath = self.classifier_savename
self.initialize_classifier(self.classifier_type.fit(self.training_data,
self.train_ground_truth))
def compute_testing_time(self, testname):
testing_time = {}
features_extraction_time = 0
if not self.online:
for count in range(len(self.parameters['descriptors'])):
try:
loaded = co.file_oper.load_labeled_data(
[str(self.features_id[count][-1])] +
self.features_file_id[count] +
[str(testname)])
(_, _, _, feat_times) = loaded
except BaseException:
return None
for key in feat_times:
LOG.info('Time:' + str(key) + ':' +
str(np.mean(feat_times[key])))
features_extraction_time += np.mean(feat_times[key])
try:
testing_time['Classification'] = self.time[
-1] / float(self.scores.shape[0])
except IndexError:
testing_time['Classification'] = (
co.file_oper.load_labeled_data(
['Testing'] + self.tests_ids[
self.available_tests.index(
testname)])['TestTime'][
'Classification'])
else:
testing_time['Classification'] = np.mean(self.time)
testing_time['Features Extraction'] = features_extraction_time
return testing_time
def add_action(self, name=None, data=None, visualize=False, offline_vis=False,
to_visualize=[], exit_after_visualization=False,
use_dexter=False,
action_type=None,
max_act_samples=None):
return self.action_recog.add_action(
name=name,
use_dexter=use_dexter,
action_type=self.action_type,
max_act_samples=max_act_samples,
data=data,
offline_vis=offline_vis,
to_visualize=to_visualize,
exit_after_visualization=exit_after_visualization)
def offline_testdata_processing(self, datapath):
'''
Offline testing data processing, using data in <datapath>.
'''
LOG.info('Processing test data..')
LOG.info('Extracting descriptors..')
(descriptors, _, mean_depths, test_name, _, _) = self.add_action(
name=None, data=datapath)
testdata = np.hstack(tuple(descriptors))
self.parameters['testing_params'][test_name] = test_name
self.parameters['testing_params']['current'] = test_name
return testdata
def save_plot(self, fig, lgd=None, display_all=False, info=None):
'''
<fig>: figure
<lgd>: legend of figure
<display_all>: whether to save as Total plot
Saves plot if the action resides in self.available_tests
'''
filename = None
if display_all:
testname = self.action_type.lower()
filename = os.path.join(*self.save_fold.split(os.sep)[:-1] +
['Total', testname + '.pdf'])
else:
if self.test_name is None:
self.test_name = (self.name + ' ' + self.classifiers_used).title()
if self.test_name in self.available_tests:
if self.save_fold is None:
if not self.online:
fold_name = co.file_oper.load_labeled_data(['Testing'],
just_catalog=True,
include_all_catalog=True)[
str(self.tests_ids[
self.available_tests.
index(self.test_name)])]
else:
fold_name = 'Online'
self.save_fold = os.path.join(
co.CONST['results_fold'], 'Classification', fold_name,
self.test_name)
if self.add_info is not None:
self.save_fold = os.path.join(
self.save_fold, self.add_info.replace(' ', '_').lower())
co.makedir(self.save_fold)
LOG.info('Saving to ' + self.save_fold)
if info is not None:
filename = os.path.join(
self.save_fold, (self.testname + ' ' + info +
'.pdf').replace(' ','_'))
else:
filename = os.path.join(
self.save_fold, self.testname.replace(' ','_') + '.pdf')
else:
LOG.warning('Requested figure to plot belongs to an' +
' action that does not reside in <self.'+
'available_tests> .Skipping..')
filename = None
import matplotlib.pyplot as plt
if filename is not None:
if lgd is None:
plt.savefig(filename)
else:
plt.savefig(filename,
bbox_extra_artists=(lgd,), bbox_inches='tight')
plt.close()
def plot_result(self, data, info=None, save=True, xlabel='Frames', ylabel='',
labels=None, colors=None, linewidths=None, alphas=None,
xticks_names=None, yticks_names=None, xticks_locs=None,
yticks_locs=None, markers=None, markers_sizes=None, zorders=None, ylim=None, xlim=None,
display_all=False, title=False):
'''
<data> is a numpy array dims (n_points, n_plots),
<labels> is a string list of dimension (n_plots)
<colors> ditto
'''
import matplotlib
from matplotlib import pyplot as plt
#matplotlib.rcParams['text.usetex'] = True
#matplotlib.rcParams['text.latex.unicode'] = True
# plt.style.classifiers_used('seaborn-ticks')
if len(data.shape) == 1:
data = np.atleast_2d(data).T
fig, axes = plt.subplots()
if xticks_locs is not None:
axes.set_xticks(xticks_locs, minor=True)
axes.xaxis.grid(True, which='minor')
if yticks_locs is not None:
axes.set_yticks(yticks_locs, minor=True)
axes.yaxis.grid(True, which='minor')
if xticks_names is not None:
plt.xticks(range(len(xticks_names)), xticks_names)
if yticks_names is not None:
plt.yticks(range(len(yticks_names)), yticks_names)
if markers is None:
markers = [','] * data.shape[1]
if markers_sizes is None:
markers_sizes = [10] * data.shape[1]
if colors is None:
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
if alphas is None:
alphas = data.shape[1] * [1]
if zorders is None:
zorders = data.shape[1] * [0]
while len(colors) < data.shape[1]:
colors += [tuple(np.random.random(3))]
if linewidths is None:
linewidths = [1] * data.shape[1]
lgd = None
for count in range(data.shape[1]):
if labels is not None:
axes.plot(data[:, count], label='%s' % labels[count],
color=colors[count],
linewidth=linewidths[count],
marker=markers[count], alpha=alphas[count],
zorder=zorders[count],
markersize=markers_sizes[count])
lgd = co.plot_oper.put_legend_outside_plot(axes,
already_reshaped=True)
else:
axes.plot(data[:, count],
color=colors[count],
linewidth=linewidths[count],
marker=markers[count], alpha=alphas[count],
zorder=zorders[count],
markersize=markers_sizes[count])
if title:
if info is not None:
plt.title(self.testname +
'\n Dataset: ' + self.testdataname +
'\n' + info.title())
else:
plt.title(self.testname +
'\n Dataset ' + self.testdataname)
info = ''
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if ylim is not None:
plt.ylim(ylim)
if xlim is not None:
plt.xlim(xlim)
if save:
self.save_plot(fig, lgd, display_all=display_all, info=info)
return fig, lgd, axes
def init_testing(self, data=None, online=True, save=True, load=True,
testname=None, scores_savepath=None,
scores_filter_shape=5,
std_small_filter_shape=co.CONST['STD_small_filt_window'],
std_big_filter_shape=co.CONST['STD_big_filt_window'],
testdatapath=None, save_results=True):
'''
Initializes paths and names used in testing to save, load and visualize
data.
Built as a convenience method, in case <self.run_testing> gets overriden.
'''
self.parameters['testing'] = True
self.parameters['testing_params']['online'] = online
if online:
self.reset_online_test()
else:
self.reset_offline_test()
self.scores_filter_shape = scores_filter_shape
self.std_small_filter_shape = std_small_filter_shape
self.std_big_filter_shape = std_big_filter_shape
self.online = online
if testname is not None:
self.testname = testname.title()
else:
self.testname = (self.name + ' ' + self.classifiers_used).title()
if self.add_info is not None:
self.testname += ' ' + self.add_info.title()
self.parameters['testing_params']['current'] = self.testname
if online:
if testdatapath is not None:
self.testdataname = ('online (using '
+ os.path.basename(testdatapath) + ')')
else:
self.testdataname = 'online'
else:
self.testdataname = os.path.basename(data)
if not self.online:
if self.test_ind is not None:
available_tests_ids = co.file_oper.load_labeled_data(['Testing'],
just_catalog=True,
include_all_catalog=True)
if available_tests_ids is None:
fold_name = '0'
else:
curr_test_id = self.tests_ids[self.available_tests.
index(self.test_name)]
if str(curr_test_id) in available_tests_ids:
fold_name = str(available_tests_ids[str(curr_test_id)])
else:
fold_name = str(len(available_tests_ids))
else:
self.test_name = 'Online'
try:
fold_name = os.path.join(*[co.CONST['results_fold'],
'Classification', 'Online'])
except OSError:
fold_name = '0'
if self.test_ind is not None:
self.save_fold = os.path.join(
co.CONST['results_fold'], 'Classification', self.test_name,
fold_name)
co.makedir(self.save_fold)
if save or load:
fold_name = self.classifier_folder
if scores_savepath is None:
self.scores_savepath = self.testdataname + '_scores_for_'
self.scores_savepath += self.full_info.replace(' ',