-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrainFace.py
987 lines (829 loc) · 31 KB
/
trainFace.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
'''
base code adapted from
https://towardsdatascience.com/a-guide-to-face-detection-in-python-3eab0f6b9fc1
https://medium.com/@sebastiannorena/pca-principal-components-analysis-applied-to-images-of-faces-d2fc2c083371
'''
'''
PCA model and classifiers training script
Run this script to train the PCA model, person and expression classifiers
This training script will generate and save the following files to disk:
faceDict.bin: subimages of input faces, as 2D Numpy arrays
iVectorDict.bin: flattened subimages of input faces, as 1D Numpy arrays
facesPDF.bin: flattened subimages of input faces, as Pandas Dataframe
pcaModel.bin: fitted PCA model
pcDict.bin: eigencoordinates of all faces processed with PCA, with additional keys input photo dimensions, zero mean setting (lighting compensation) and eigenspace centroid of all faces, as Python dictionary
svcModel.bin: trained SVM person classifier
adaBoostModel.bin: trained Adaboost person classifier
gradBoostModel.bin: trained gradient boosting person classifier
XGBoostModel.bin: trained XGBoost person classifier
randomForestModel.bin: trained random forest person classifier
stackingModel.bin: trained stacking generalizer person classifier
SSDModel.bin: trained Nearest Neighbour person classifier
3NNModel.bin: trained Nearest Neighbour person classifier, K = 3
5NNModel.bin: trained Nearest Neighbour person classifier, K = 5
ELMMLPModel.bin: trained ELM (MLP Hidden Layer) person classifier
ELMRBFModel.bin: trained ELM (RBF Hidden Layer) person classifier
expressionSSDstore.bin: nested list of expressions, containing list of SSD of eigencoordinates to centroid of that particular expressions
AdaboostExpressionsModel.bin: trained Adaboost expression classifier
svcExpressionsModel.bin: trained SVM expression classifier
rfExpressionsModel.bin: trained SVM expression classifier
centroidKNNExpressionsModel.bin: trained centroid based K-NN expression classifier
SSDExpressionsModel.bin: Nearest Neighbour classifier
7NNExpressionsModel.bin: K-NN expression classifier, K = 7
10NNExpressionsModel.bin: K-NN expression classifier, K = 10
15NNExpressionsModel.bin: K-NN expression classifier, K = 15
20NNExpressionsModel.bin: K-NN expression classifier, K = 20
20NNExpressionsModel.bin: K-NN expression classifier, K = 20
XGBoostExpression.bin: trained XGBoost expression classifer
Script variables used for settings:
reTrainAll: set to true to
Run face cropping from input folder
Fit PCA model
Project all faces in input photos to eigenspace
faceDictLoad: load cropped face images instead of scanning input photos folder
pcaModelLoad: load pre-fitted PCA model. PCA expected dimensions will be loaded as well. If photos were zero-meaned, the setting will be loaded as well.
pcaDataLoad: load eigencoordinates of faces in training set
disableTrainTestSplit: all input photos will be used to train classifiers. Enable this mode when training classifiers to be deployed for real-time/historical video detection. Disable this mode if evaluating classifier performance using input photos
showIndividualPredictions: display each individual prediction by classifiers for debugging
displayUnstableDetects: display flagged subimages if mulitple faces are detected in an input photo
Person and expression classifiers are always retrained when this script is run.
To exclude certain people for person classifiers, make use of script 'adjustDict.py'.
Indicate which people are to be removed in that script.
Train person classifiers on the reduced person set by placing the adjusted pcDict.bin in the same directory while setting reTrainAll parameter in this script to False
use python3 command to execute!
'''
import cv2
import matplotlib.pyplot as plt
import dlib
from imutils import face_utils
from rxPCA import PCA
import numpy as np
import pandas as pd
from joblib import dump, load
import time
font = cv2.FONT_HERSHEY_SIMPLEX
dataLoc = "/Users/foorx/opencv/venv/lib/python3.6/site-packages/cv2/data"
cascPath = dataLoc + "/haarcascade_frontalface_default.xml"
eyePath = dataLoc + "/haarcascade_eye.xml"
smilePath = dataLoc + "/haarcascade_smile.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
eyeCascade = cv2.CascadeClassifier(eyePath)
smileCascade = cv2.CascadeClassifier(smilePath)
import glob
import random
# folder where training images are located
path = "./input/"
# extension of training images
fileExt = ".jpg"
files = glob.glob(path+"*"+fileExt)
files = list(map(lambda file: file.strip(), files)) #strip white spaces from filename
couldNotDetects = list()
unstableDetects = list()
faceDict = dict() #stores subimages of detected faces
iVectorDict = dict() #stores vectors of faces in image space
pcDict = dict() #stores principal components of each face in eigenspace
#use zero mean
useZeroMean = True
#resize subimage
dim = (100, 100) #width, height
#set to false to update models and dictionaries
reTrainAll = True
faceDictLoad = not reTrainAll
pcaModelLoad = not reTrainAll
pcaDataLoad = not reTrainAll
disableTrainTestSplit = False
showIndividualPredictions = False
displayUnstableDetects = False
processedFiles = list()
if faceDictLoad == False:
for file in files:
input = file
# input = input.split('_') #convert to this instead
# person = input[0][len(path):] #class
# subclass = input[1].split('.')[0] #type of photo
person = input[len(path):-len(fileExt)]
print("Person:")
print(person)
gray = cv2.imread(file,0)
# Detect faces in input image
faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=8,flags=cv2.CASCADE_SCALE_IMAGE)
print("Count of faces: " + str(len(faces)))
face = None
#attempt to eliminate false positives, only take first face
if len(faces):
processedFiles.append(person)
if len(faces)>1:
unstableDetects.append(person)
face = faces[0]
########process subimage########
x = face[0]
y = face[1]
w = face[2]
h = face[3]
#get subimage as square
ext = min([max([w,h]), np.shape(gray)[0]-x, np.shape(gray)[1]]-y)
# extract subimage containing face
subImage = gray[y:(y+h),x:(x+w)]
#resize subimage
subImage = cv2.resize(subImage, dim)
#vector of pixels for each face
faceVector = subImage.flatten('C')
if useZeroMean == True:
#apply zero mean to remove brightness bias
faceVector = faceVector-np.mean(faceVector)
#add subImage to dictionary
faceDict[person] = subImage
#add facevector to dictionary
iVectorDict[person] = faceVector
else:
print("Failed to detect face in image")
couldNotDetects.append(person)
print("Could not detects:")
for person in couldNotDetects:
print(person)
print("Unstable detections:")
for person in unstableDetects:
print(person)
# display images with unstable detections
if displayUnstableDetects:
plt.figure(figsize=(8,8))
plt.imshow(faceDict[person], cmap='gray')
plt.show()
print("Number of faces in faceDict: " + str(len(faceDict)))
dump(faceDict, 'faceDict.bin')
dump(iVectorDict, 'iVectorDict.bin')
else:
print("loaded processed subimages from disk")
faceDict = load('faceDict.bin') #load subimages of detected faces
iVectorDict = load('iVectorDict.bin') #load vectors of faces in image space
if pcaModelLoad == False:
#determing principal components
print("Performing PCA on dataset")
pcaModel = PCA(n_components=0.95)
facesPDF = pd.DataFrame(list(iVectorDict.values()))
dump(facesPDF, 'facesPDF.bin')
print("number of detected faces")
print(len(facesPDF))
if (len(facesPDF) == 0):
raise ValueError
pcaModel.fit(facesPDF)
dump(pcaModel, 'pcaModel.bin')
else:
print("Loading PCA model from disk")
pcaModel = load('pcaModel.bin')
if pcaDataLoad == False:
print("Calcuating Principal Components of faces")
t = time.time()
for person, personIndex in zip(iVectorDict, range(len(iVectorDict))):
print("Image Index:")
print(personIndex)
pcDict[person] = pcaModel.transform(pd.DataFrame(list(iVectorDict[person])))
print(person)
print(pcDict[person])
elapsed = time.time() - t
print("Dataset projection time: " + str(elapsed) + 'seconds')
print(elapsed)
ignoreKeys = ['useZeroMean', 'dim', 'facesCentroid']
try:
del accumulator
except:
pass
for key,value in pcDict.items():
if key not in ignoreKeys:
if 'accumulator' not in globals():
accumulator = value
else:
accumulator = np.add(accumulator,value)
facesCentroid = accumulator.tolist()
pcDict['facesCentroid'] = facesCentroid
pcDict['useZeroMean'] = useZeroMean
pcDict['dim'] = dim
dump(pcDict, 'pcDict.bin')
del pcDict['facesCentroid']
del pcDict['useZeroMean']
del pcDict['dim']
print("number of trained faces")
print(len(pcDict))
else:
print("Loading pcDict from disk")
pcDict = load('pcDict.bin')
facesCentroid = pcDict['facesCentroid']
del pcDict['facesCentroid']
del pcDict['useZeroMean']
del pcDict['dim']
print("Number of photos: " + str(len(pcDict)))
persons = set(map(lambda label: label.split('_')[0],pcDict.keys()))
print("Number of people: " + str(len(persons)))
print(persons)
X, y, expressionsy = [],[],[]
for fileName, eigenCoordinates in pcDict.items():
X.append(eigenCoordinates)
y.append(fileName.split('_')[0])
expressionsy.append(fileName.split('_')[1])
expressionsX, newExpressionsy = [],[]
for eigenCoordinates, expression in zip(X, expressionsy):
if not expression.isnumeric():
expressionsX.append(eigenCoordinates)
newExpressionsy.append(expression)
expressionsy = newExpressionsy
expressions = set(expressionsy)
print("Number of expressions: " + str(len(expressions)))
print(expressions)
print("Breakdown of person labels in training set (before train test split)")
personLabelCount = {}
for key in set(y):
personLabelCount[key] = 0
for label in y:
personLabelCount[label]+=1
print(personLabelCount)
print("Breakdown of expression labels in training set (before train test split)")
expressionLabelCount = {}
for key in set(expressionsy):
expressionLabelCount[key] = 0
for label in expressionsy:
expressionLabelCount[label]+=1
print(expressionLabelCount)
from sklearn.model_selection import train_test_split
test_size=0.2
#split for persons classes
trainX, testX, trainy, testy = train_test_split(X, y, test_size=test_size)
if disableTrainTestSplit:
trainX, trainy = X, y
#split for expressions classes
expressionsTrainX, expressionsTestX, expressionsTrainy, expressionsTesty = train_test_split(expressionsX, expressionsy, test_size=test_size)
if disableTrainTestSplit:
expressionsTrainX, expressionsTrainy = expressionsX, expressionsy
if disableTrainTestSplit:
print("TRAIN TEST SPLIT DISABLED")
else:
print("Train test split: ")
print("Test size = " + str(test_size*100) + "%")
print("Breakdown of person labels in training set")
personLabelCount = {}
for key in set(trainy):
personLabelCount[key] = 0
for label in trainy:
personLabelCount[label]+=1
print(personLabelCount)
print("Breakdown of person labels in test set")
personLabelCount = {}
for key in set(testy):
personLabelCount[key] = 0
for label in testy:
personLabelCount[label]+=1
print(personLabelCount)
print("Breakdown of expression labels in training set")
personLabelCount = {}
for key in set(expressionsTrainy):
personLabelCount[key] = 0
for label in expressionsTrainy:
personLabelCount[label]+=1
print(personLabelCount)
print("Breakdown of expression labels in test set")
personLabelCount = {}
for key in set(expressionsTesty):
personLabelCount[key] = 0
for label in expressionsTesty:
personLabelCount[label]+=1
print(personLabelCount)
#####SVM#####
from sklearn.svm import SVC as classifier
model = classifier(kernel='linear',C=0.025)
model.fit(trainX,trainy)
dump(model, 'svcModel.bin')
print("##########Testing person identification with SVM model##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####Adaboost#####
from sklearn.ensemble import AdaBoostClassifier as classifier
from sklearn.tree import DecisionTreeClassifier
model = classifier(base_estimator = DecisionTreeClassifier(max_depth=2),
n_estimators=600,
learning_rate=1, random_state=0)
model.fit(trainX,trainy)
dump(model, 'adaBoostModel.bin')
print("##########Testing person identification with Adaboost model##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####GradientBoosting#####
from sklearn.ensemble import GradientBoostingClassifier as classifier
model = classifier()
model.fit(trainX,trainy)
dump(model, 'gradBoostModel.bin')
print("##########Testing person identification with GradientBoosting model##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####XGBoost#####
from xgboost import XGBClassifier as classifier
model = classifier()
model.fit(np.array(trainX),np.array(trainy))
dump(model, 'XGBoostModel.bin')
print("##########Testing person identification with XGBoost model##########")
predictions = model.predict(np.array(testX))
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####Random Forest#####
from sklearn.ensemble import RandomForestClassifier as classifier
model = classifier()
model.fit(trainX,trainy)
dump(model, 'randomForestModel.bin')
print("##########Testing person identification with Random Forest model##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####Stacking Classifier#####
from sklearn.ensemble import StackingClassifier as classifier
from sklearn.ensemble import RandomForestClassifier
# from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
estimators = [('rf', RandomForestClassifier()),('svc', SVC(kernel='linear',C=0.025))]
model = classifier(estimators = estimators, final_estimator=SVC(kernel='linear',C=0.025))
model.fit(trainX,trainy)
dump(model, 'stackingModel.bin')
print("##########Testing person identification with Stacking Classifier model with log reg as final estimator##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
'''
#####HistGradientBoostingClassifier#####
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistGradientBoostingClassifier as classifier
model = classifier()
model.fit(trainX,trainy)
dump(model, 'histGradBoostingModel.bin')
print("##########Testing person identification with HistGradientBoostingClassifier model##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
'''
#####K-NN, n=1#####
from sklearn.neighbors import KNeighborsClassifier as classifier
model = classifier(n_neighbors=1)
model.fit(trainX,trainy)
dump(model, 'SSDModel.bin')
print("##########Testing person identification with K-NN model, K = 1 (SSD)##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####K-NN, n=5#####
from sklearn.neighbors import KNeighborsClassifier as classifier
model = classifier(n_neighbors=5)
model.fit(trainX,trainy)
dump(model, '5NNModel.bin')
print("##########Testing person identification with K-NN model, K = 5##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####K-NN, n=3#####
from sklearn.neighbors import KNeighborsClassifier as classifier
model = classifier(n_neighbors=3)
model.fit(trainX,trainy)
dump(model, '3NNModel.bin')
print("##########Testing person identification with K-NN model, K = 3##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####ELM with MLP Random Layer#####
from random_layer import MLPRandomLayer
from elm import GenELMClassifier as classifier
def powtanh_xfer(activations, power=1.0):
return pow(np.tanh(activations), power)
model = classifier(hidden_layer=MLPRandomLayer(n_hidden=100, activation_func=powtanh_xfer, activation_args={'power':3.0}))
model.fit(trainX,trainy)
dump(model, 'ELMMLPModel.bin')
print("##########Testing person identification with ELM with MLP Random Layer model##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####ELM with RBF Random Layer#####
from random_layer import RBFRandomLayer
from elm import GenELMClassifier as classifier
model = classifier(hidden_layer=RBFRandomLayer(n_hidden=100, random_state=0, rbf_width=0.01))
model.fit(trainX,trainy)
dump(model, 'ELMRBFModel.bin')
print("##########Testing person identification with ELM with RBF Random Layer model##########")
predictions = model.predict(testX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, testy):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####calculate SSD for each expression#####
expressionSSDstore = {}
for expression in expressions:
expressionSSDstore[expression] = []
for coordinate, label in zip(expressionsX, expressionsy):
SSD = np.sum(np.subtract(facesCentroid, coordinate).flatten()**2)
print(label + " " +str(SSD))
expressionSSDstore[label].append(SSD)
from statistics import mean, median
for expression in expressions:
print(expression)
print(expressionSSDstore[expression])
print("median:")
print(median(expressionSSDstore[expression]))
print("mean:")
print(mean(expressionSSDstore[expression]))
print("\n")
dump(expressionSSDstore, 'expressionSSDstore.bin')
#####Adaboost for expressions#####
from sklearn.ensemble import AdaBoostClassifier as classifier
from sklearn.tree import DecisionTreeClassifier
model = classifier(base_estimator = DecisionTreeClassifier(max_depth=2),
n_estimators=600,
learning_rate=1, random_state=0)
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, 'AdaboostExpressionsModel.bin')
print("##########Testing Expressions Adaboost model##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####SVM for expressions#####
from sklearn.svm import SVC as classifier
model = classifier(kernel='linear',C=0.025)
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, 'svcExpressionsModel.bin')
print("##########Testing Expressions SVM model##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####Random Forest for expressions#####
from sklearn.ensemble import RandomForestClassifier as classifier
model = classifier()
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, 'rfExpressionsModel.bin')
print("##########Testing Expressions Random Forest model##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####expression K-NN centroid#####
from sklearn.neighbors import NearestCentroid as classifier
model = classifier()
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, 'centroidKNNExpressionsModel.bin')
print("##########Testing expression K-NN centroid model##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####expression SSD#####
from sklearn.neighbors import KNeighborsClassifier as classifier
model = classifier(n_neighbors=1)
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, 'SSDExpressionsModel.bin')
print("##########Testing expression SSD model##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####expression K-NN, n=10#####
from sklearn.neighbors import KNeighborsClassifier as classifier
model = classifier(n_neighbors=10)
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, '10NNExpressionsModel.bin')
print("##########Testing expression K-NN model, K = 10##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####expression K-NN, n=20#####
from sklearn.neighbors import KNeighborsClassifier as classifier
model = classifier(n_neighbors=20)
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, '20NNExpressionsModel.bin')
print("##########Testing expression K-NN model, K = 20##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####expression K-NN, n=15#####
from sklearn.neighbors import KNeighborsClassifier as classifier
model = classifier(n_neighbors=15)
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, '15NNExpressionsModel.bin')
print("##########Testing expression K-NN model, K = 15##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####expression K-NN, n=7#####
from sklearn.neighbors import KNeighborsClassifier as classifier
model = classifier(n_neighbors=7)
model.fit(expressionsTrainX,expressionsTrainy)
dump(model, '7NNExpressionsModel.bin')
print("##########Testing expression K-NN model, K = 7##########")
predictions = model.predict(expressionsTestX)
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")
#####XGBoost#####
from xgboost import XGBClassifier as classifier
model = classifier()
model.fit(np.array(expressionsTrainX),np.array(expressionsTrainy))
dump(model, 'XGBoostExpression.bin')
print("##########Testing expression XGBoost model##########")
predictions = model.predict(np.array(expressionsTestX))
rights, wrongs = 0,0
for prediction, actual in zip(predictions, expressionsTesty):
if prediction == actual:
if showIndividualPredictions:
print(prediction)
print("Correct!")
rights+=1
else:
if showIndividualPredictions:
print(prediction + ' vs ' + actual)
print("Wrong!")
wrongs+=1
print("Rights: " + str(rights))
print("Wrongs:" + str(wrongs))
print("Score: " + str(rights/(rights+wrongs)*100) + "%")
print("\n")