-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaja1032_ml_final_2.py
1231 lines (942 loc) · 44.6 KB
/
maja1032_ml_final_2.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
# -*- coding: utf-8 -*-
"""maja1032_ML-Final_2.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1aM6JLaxuOlXL77b2C7OzEnwA-ZcxsBpB
"""
get_ipython().system('git clone https://github.com/JaMa-95/ML-Final.git')
"""# Final Projext Machine Learning in Python
**Jakob Mattes**
**Maja1032@hs-karlsruhe.de**
**75269**
Made with google colab
"""
import numpy as np
import pandas as pd
import os
import cv2
import random
from tqdm import tqdm
from tensorflow.keras import applications
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, BatchNormalization, Dropout, MaxPool3D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#library np_utils to make labels categorical
from tensorflow.python.keras.utils import np_utils
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras import optimizers
import matplotlib.pyplot as plt
categories = ['dog', 'panda', 'cat']
X_train, X_test = [], []
y_train, y_test = [], []
imagePaths = []
HEIGHT = 32
WIDTH = 55
N_CHANNELS = 3
########################################################################
########Changed the file path because of google colab###################
########################################################################
# load training data
for k, category in enumerate(categories):
for f in os.listdir('/content/ML-Final/data/train/' + category):
imagePaths.append(['/content/ML-Final/data/train/' + category+'/'+f, k])
# loop over the input images
for imagePath in tqdm(imagePaths):
if 'ds_store' in imagePath[0].lower():
continue
# load the image, resize the image to be HEIGHT * WIDTH pixels (ignoring
# aspect ratio) and store the image in the data list
image = cv2.imread(imagePath[0])
image = cv2.resize(image, (WIDTH, HEIGHT)) # .flatten()
X_train.append(image)
# extract the class label from the image path and update the
# labels list
label = imagePath[1]
y_train.append(label)
# load test data
imagePaths = []
for k, category in enumerate(categories):
for f in os.listdir('/content/ML-Final/data/test/' + category):
imagePaths.append(['/content/ML-Final/data/test/' + category+'/'+f, k])
# loop over the input images
for imagePath in tqdm(imagePaths):
if 'ds_store' in imagePath[0].lower():
continue
# load the image, resize the image to be HEIGHT * WIDTH pixels (ignoring
# aspect ratio) and store the image in the data list
image = cv2.imread(imagePath[0])
image = cv2.resize(image, (WIDTH, HEIGHT)) # .flatten()
X_test.append(image)
# extract the class label from the image path and update the
# labels list
label = imagePath[1]
y_test.append(label)
X_train, X_test, y_train, y_test = np.array(X_train), np.array(X_test), np.array(y_train), np.array(y_test)
############
# Create here your code. X_train, X_test, and so on is already given and splitted.
#Make y_train and y_test categorical (three dimensional vector)
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
#DataGenerator
datagen = ImageDataGenerator(
featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
zca_epsilon=1e-06,
rotation_range=30,
width_shift_range=0.1,
height_shift_range=0.1,
brightness_range=None,
shear_range=0.0,
zoom_range=0.2,
channel_shift_range=0.0,
fill_mode='nearest',
cval=0.0,
horizontal_flip=True,
vertical_flip=True,
rescale=1./255,
preprocessing_function=None,
data_format=None,
validation_split=0.0,
dtype=None
)
datagen_test = ImageDataGenerator(rescale=1./255, samplewise_center=True)
#Fit datagen to training data
datagen.fit(X_train)
# Tried to normalize data but no better progress
#X_train = np.array(X_train)/255
#X_test = np.array(X_test)/255
#y_train = np.array(y_train)/255
#y_test = np.array(y_test)/255
X_train.shape
#train_flow = datagen.flow_from_dataframe(X_train, x_col ='Filepath', y_col ='Target', target_size=(WIDTH, HEIGHT),interpolation='lanczos', validate_filenames = False)
"""# **Self Made Model Start here**
**Selfmade Model 1**
Good Accuracy/ Bad Val_Accuracy
"""
# Define our CNN
model = Sequential()
model.add(Conv2D(32, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(BatchNormalization())
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(256 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate to adam optimizer
opt = optimizers.Adam(learning_rate=0.00001)
#apply decay rate to optimizer
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=1e-5,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping (not used)
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. with 1000 epochs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 35) ,epochs = 1000 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of the model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model accuracy')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""**Selfmade Model 2**
Fewer Neurons
"""
# Define our CNN
model = Sequential()
model.add(Conv2D(32, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(40 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.6)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(54 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.4)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(40 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate to adam optimizer
opt = optimizers.Adam(learning_rate=0.0001)
#apply decay rate to optimizer
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=1e-5,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. Used 300 epochs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 35) ,epochs = 300 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of th9e model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model accuracy')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""**Selfmade Model 3**
Best Validation Accu
"""
# Define our CNN
model = Sequential()
model.add(Conv2D(32, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(40 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate to adam optimizer
opt = optimizers.Adam(learning_rate=0.0001)
#apply decay rate
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=1e-5,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping (Not used)
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. Used 300 epochs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 35) ,epochs = 300 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of th9e model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model accuracy')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""**Selfmade Model 4**
Very Unstable/ Reaches test Accu
"""
model = Sequential()
model.add(Conv2D(32, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(256 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((3,3) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate
opt = optimizers.Adam(learning_rate=0.0001)
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=0.0001,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. 100 epichs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 35) ,epochs = 100 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of th9e model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""**Selfmade Model 5**"""
# Define our CNN
model = Sequential()
model.add(Conv2D(32, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(40 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate
opt = optimizers.Adam(learning_rate=0.0001)
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=1e-5,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. 300 epochs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 35) ,epochs = 300 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of th9e model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model accuracy')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""**Selfmade Model 6**
Higher Dropout Rate
More stable but lower test accuracy
"""
# Define our CNN
model = Sequential()
model.add(Conv2D(32, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(Dropout(0.3)) # Dropout is optional.
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.4)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.4)) # Dropout is optional.
model.add(Dropout(0.3)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(40 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.3)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate
opt = optimizers.Adam(learning_rate=0.0001)
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=0.0001,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. 200 epichs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = bs) ,epochs = 200 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of the model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
print(bs)
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
plt.savefig('loss'+str(bs)+'.png')
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
plt.savefig('accuracy'+str(bs)+'.png')
"""**Selfmade Model 7**
"""
# Define our CNN
model = Sequential()
model.add(Conv2D(32, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(Dropout(0.5)) # Dropout is optional.
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.5)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.6)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(256 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(256 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.6)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.5)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate
opt = optimizers.Adam(learning_rate=0.0001)
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=0.0001,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. 50 epichs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 32) ,epochs = 50 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of the model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
plt.xlim([0, 1])
"""**Selfmade Model 8**
Small Network high Dropout
"""
# Define our CNN
model = Sequential()
model.add(Conv2D(16, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(Dropout(0.1)) # Dropout is optional.
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.5)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(16, activation='relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate
opt = optimizers.Adam(learning_rate=0.00005)
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=0.0001,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. 100 epichs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 32) ,epochs = 100 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of the model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""**Selfmade Model 9**
Smal Network
"""
# Define our CNN
model = Sequential()
model.add(Conv2D(16, (3,3), strides=1, padding='same', activation='relu', input_shape=X_train.shape[1:],kernel_regularizer='l2')) # this layer has 32 filters. The filter size is: (3,3)
model.add(BatchNormalization()) # This is optional to avoid overfitting
model.add(Dropout(0.1)) # Dropout is optional.
model.add(MaxPool2D((2,2), strides=2, padding='same'))
model.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))
model.add(Dropout(0.5)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
model.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))
model.add(Flatten())
model.add(Dense(16, activation='relu'))
model.add(Dropout(0.1)) # Dropout is optional.
model.add(BatchNormalization()) # BatchNormalization is optional
# Use softmax and 3 ouput layers because of three labels
model.add(Dense(3, activation='softmax'))
#apply learning rate
opt = optimizers.Adam(learning_rate=0.00005)
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=0.0001,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. 500 epichs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 32) ,epochs = 500 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of the model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""# **Application Model start here**
**VGG16**
"""
# load existing CNN from tensorflow. Here we use VGG16, pretrained on imagenet. we will not include_top.
# include_top means the flatten layer + the following dense layers. Wen only use the CNN-blocks from this network.
model = applications.VGG16(weights='imagenet', include_top=False, input_shape=X_train.shape[1:])
flat1 = Flatten()(model.output) # add a flatten to the VGG16
class1 = Dense(256, activation='relu')(flat1) # add a Dense layer after the flatten
# Use softmax and 3 ouput layers because of three labels
output = Dense(3, activation='softmax')(class1)
model = Model(inputs=model.inputs, outputs=output) # define our final model. The first part is from VGG16 and the output is the layer defined above
#apply learning rate
opt = optimizers.Adam(learning_rate=0.00005)
lr_schedule = optimizers.schedules.ExponentialDecay(
initial_learning_rate=1e-5,
decay_steps=10000,
decay_rate=0.9)
optimizer = optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) # make sure we have categorical_crossentropy as loss
model.summary()
#Early stopping
es_callback = EarlyStopping(monitor='val_loss', patience=3)
#fit call to use the datagen. 30 epichs
diagramm = model.fit(datagen.flow(X_train,y_train, batch_size = 35) ,epochs = 30 , validation_data = (X_test, y_test))
#Evaluation part; printing accuracy
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print('Train Accuracy of the model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""**ResNet152V2**"""
# load existing CNN from tensorflow. Here we use VGG16, pretrained on imagenet. we will not include_top.
# include_top means the flatten layer + the following dense layers. Wen only use the CNN-blocks from this network.
model = applications.ResNet152V2(weights='imagenet', include_top=False, input_shape=X_train.shape[1:] ,kernel_regularizer='l2')
flat1 = Flatten()(model.output) # add a flatten to the VGG16
class1 = Dense(256, activation='relu')(flat1) # add a Dense layer after the flatten
# Use softmax and 3 ouput layers because of three labels
output = Dense(3, activation='softmax')(class1) # add a dense layer after the 256-dense layer
model = Model(inputs=model.inputs, outputs=output) # define our final model. The first part is from VGG16 and the output is the layer defined above
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
model.fit(datagen.flow(X_train,y_train, batch_size = 32) ,epochs = 10 , validation_data = (X_test, y_test))
y_pred_model1 = np.argmax(model.predict(X_test), axis=-1)
y_test_model1 = np.argmax(y_test, axis=-1)
y_train_model1 = np.argmax(y_train, axis=-1)
print("Resnet152")
print('Train Accuracy of the model is', accuracy_score(y_train_model1, np.argmax(model.predict(X_train), axis=-1)))
print('Test Accuracy of the model is', accuracy_score(y_test_model1, y_pred_model1))
# Plot accuracy graph
plt.plot(diagramm.history['accuracy'])
plt.plot(diagramm.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
# Plot loss graph
plt.plot(diagramm.history['loss'])
plt.plot(diagramm.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
"""**EfficientNetB7**"""
# load existing CNN from tensorflow. Here we use VGG16, pretrained on imagenet. we will not include_top.
# include_top means the flatten layer + the following dense layers. Wen only use the CNN-blocks from this network.
model = applications.EfficientNetB7(weights='imagenet', include_top=False, input_shape=X_train.shape[1:])