-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree_classification_NN.py
746 lines (477 loc) · 19.3 KB
/
tree_classification_NN.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
#!/usr/bin/env python
# coding: utf-8
# # Tree species classification project -- Data Science of Earth Oberservation
# Group members:
#
#
# Input file: .npy
# In[1]:
# import the libraries you need
import os
import math
import numpy as np
import pandas as pd
import rasterio
from tqdm import tqdm
import requests
import matplotlib.pyplot as plt
import glob
import matplotlib.image as mpimg
from matplotlib.image import imread
from itertools import product
from PIL import Image
from itertools import chain
import json
from jsonpath import jsonpath
from matplotlib.colors import Normalize
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.metrics import accuracy_score
from sklearn.utils.multiclass import type_of_target
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, models
import torch
# Folium setup.
import folium
# # Step 1. Input the npy data
# In[11]:
# get all npy files
## The ratio can also be changed
path= '/Users/siruiwang/Documents/ESPACE-LECTURE/3rd_semester/Data science of earth observation/Project_data_science/data0121/npy/'
split_ratio = 0.8
dir_samples = path + "/*.npy"
samples = glob.glob(dir_samples)
# merge them
t_samples = np.load(samples[0], allow_pickle=True)
for i, p in tqdm(enumerate(samples[1:])):
try:
t_samples = np.concatenate(
(t_samples, np.load(p, allow_pickle=True))
)
except Exception:
print(p)
np.random.shuffle(t_samples,)
train_num = int(len(t_samples)*split_ratio)
t_sample = t_samples[:train_num]
v_sample = t_samples[train_num:]
# define the train/valid path
t_samples_merge_path = path + "merge/train_merge.npy"
v_samples_merge_path = path + "merge/val_merge.npy"
np.save(t_samples_merge_path, t_sample)
np.save(v_samples_merge_path, v_sample)
print("Now all merge samples are saved!")
# # Step 2. Data preparation
# In[12]:
train_merge = np.load(t_samples_merge_path,allow_pickle=True)
val_merge = np.load(v_samples_merge_path,allow_pickle=True)
print (np.array(train_merge).shape)
print (np.array(val_merge).shape)
# In[13]:
kernel=9
bands=40
output_size = 8
number_samples = train_merge.shape[0]
data_train = train_merge[:,:,0]
X_train= np.zeros((number_samples, kernel,kernel,bands), dtype=float)
for i in range(0,number_samples-1):
X_train[i,:] = data_train[i,0]
Y_train = np.reshape(train_merge[:,:,1],number_samples).astype(int)
# In[14]:
number_samples = val_merge.shape[0]
data_val = val_merge[:,:,0]
X_val= np.zeros((number_samples, kernel,kernel,bands), dtype=float)
for i in range(0,number_samples-1):
X_val[i,:] = data_val[i,0]
Y_val = np.reshape(val_merge[:,:,1],number_samples).astype(int)
# In[15]:
number_samples = X_train.shape[0]
X_train_rf = np.reshape(X_train, (number_samples, kernel*kernel*bands))
X_train_rf= np.array(pd.DataFrame(X_train_rf).fillna(0))
print("Post-processed S2_train data shape: ", X_train_rf.shape)
# In[16]:
number_samples_v = X_val.shape[0]
X_val_rf = np.reshape(X_val, (number_samples_v, kernel*kernel*bands))
X_val_rf= np.array(pd.DataFrame(X_val_rf).fillna(0))
print("Post-processed S2_val data shape: ", X_val_rf.shape)
# # Step 3. Random forest classification
#
# Random Forest: Random Forest is a supervised learning algorithm, it can be used to classify tree species using Sentinel-2 imagery.
# In[17]:
rf_classifier = RandomForestClassifier(random_state=0)
rf_classifier.fit(X_train_rf, Y_train)
# In[18]:
y_pred_rf = rf_classifier.predict(X_val_rf)
# In[19]:
ConfusionMatrixDisplay.from_predictions(Y_val, y_pred_rf)
plt.show()
acc_rf = accuracy_score(Y_val, y_pred_rf)
print("Accuracy Random Forest Classifier: ", acc_rf)
# # Step 4. Artificial Nueral Network (ANN) classification
# In[118]:
number_samples = X_train.shape[0]
X_train_nn= np.zeros((number_samples, kernel*kernel,bands), dtype=float)
for i in range(0,number_samples-1):
X_train_nn[i,:] = np.reshape(X_train[i,:], ( kernel*kernel,bands))
X_train_nn[i,:]= np.array(pd.DataFrame(X_train_nn[i,:]).fillna(0))
print("Post-processed S2_train data shape: ", X_train_nn.shape)
# In[102]:
number_samples = X_train.shape[0]
X_train_nn0= np.zeros((number_samples, kernel,4,kernel,bands), dtype=float)
X_train_nn1= np.zeros((number_samples, kernel*4,kernel,4,bands), dtype=float)
X_train_nn2= np.zeros((number_samples, kernel*4,kernel,bands), dtype=float)
X_train_nn3= np.zeros((number_samples, kernel*4,kernel*4,bands), dtype=float)
for i in range(0,number_samples-1):
X_train_nn0[i,:] = np.stack((np.array(X_train[i,:]),np.array(X_train[i,:]),np.array(X_train[i,:]),np.array(X_train[i,:])),axis=1)
X_train_nn2[i,:] = np.reshape(X_train_nn0[i,:], ( kernel*4,kernel,bands))
X_train_nn1[i,:] = np.stack((np.array(X_train_nn2[i,:]),np.array(X_train_nn2[i,:]),np.array(X_train_nn2[i,:]),np.array(X_train_nn2[i,:])),axis=2)
X_train_nn3[i,:] = np.reshape(X_train_nn1[i,:], ( kernel*4,kernel*4,bands))
# X_train_nn2[i,:]= np.array(pd.DataFrame(X_train_nn2[i,:]).fillna(0))
#X_train_nn2[i,:]= np.array(pd.DataFrame(X_train_nn2[i,:]).fillna(0))
print("Post-processed S2_train data shape: ", X_train_nn3.shape)
# In[103]:
number_samples = X_val.shape[0]
X_val_nn0= np.zeros((number_samples, kernel,4,kernel,bands), dtype=float)
X_val_nn1= np.zeros((number_samples, kernel*4,kernel,4,bands), dtype=float)
X_val_nn2= np.zeros((number_samples, kernel*4,kernel,bands), dtype=float)
X_val_nn3= np.zeros((number_samples, kernel*4,kernel*4,bands), dtype=float)
for i in range(0,number_samples-1):
X_val_nn0[i,:] = np.stack((np.array(X_val[i,:]),np.array(X_val[i,:]),np.array(X_val[i,:]),np.array(X_val[i,:])),axis=1)
X_val_nn2[i,:] = np.reshape(X_val_nn0[i,:], ( kernel*4,kernel,bands))
X_val_nn1[i,:] = np.stack((np.array(X_val_nn2[i,:]),np.array(X_val_nn2[i,:]),np.array(X_val_nn2[i,:]),np.array(X_val_nn2[i,:])),axis=2)
X_val_nn3[i,:] = np.reshape(X_val_nn1[i,:], ( kernel*4,kernel*4,bands))
# X_train_nn2[i,:]= np.array(pd.DataFrame(X_train_nn2[i,:]).fillna(0))
#X_train_nn2[i,:]= np.array(pd.DataFrame(X_train_nn2[i,:]).fillna(0))
print("Post-processed S2_train data shape: ", X_val_nn3.shape)
# In[112]:
input_size=( kernel*kernel,bands)
# In[117]:
number_samples = X_val.shape[0]
X_val_nn= np.zeros((number_samples, kernel*kernel,bands), dtype=float)
for i in range(0,number_samples-1):
X_val_nn[i,:] = np.reshape(X_val[i,:], ( kernel*kernel,bands))
X_val_nn[i,:]= np.array(pd.DataFrame(X_val_nn[i,:]).fillna(0))
print("Post-processed S2_train data shape: ", X_val_nn.shape)
# In[123]:
simple_model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=input_size),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(output_size, activation='softmax')
])
simple_model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# In[124]:
class SelectiveProgbarLogger(tf.keras.callbacks.ProgbarLogger):
def __init__(self, verbose, epoch_interval, *args, **kwargs):
super().__init__(*args, **kwargs)
self.default_verbose = verbose
self.epoch_interval = epoch_interval
def on_epoch_begin(self, epoch, *args, **kwargs):
self.verbose = (
0
if epoch % self.epoch_interval != 0
else self.default_verbose
)
super().on_epoch_begin(epoch, *args, **kwargs)
# In[125]:
history = simple_model.fit(X_train_nn, Y_train, epochs=200,callbacks=[SelectiveProgbarLogger(verbose = 1,epoch_interval=20)], verbose=0,validation_data=(X_val_nn, Y_val))
# In[126]:
y_pred_dl_p = simple_model.predict(X_val_nn)
print("Prediction example: ", y_pred_dl_p[0,:], " Class: ", np.argmax(y_pred_dl_p[0,:]))
# In[127]:
y_pred_dl = np.argmax(y_pred_dl_p, axis=1)
ConfusionMatrixDisplay.from_predictions(Y_val, y_pred_dl)
plt.show()
acc_dl = accuracy_score(Y_val, y_pred_dl)
print("Accuracy Simple Deep Learning model: ", acc_dl)
# In[128]:
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()),1])
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0,1.0])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()
# In[129]:
fine_tune_epochs = 200
initial_epochs = 10
total_epochs = initial_epochs + fine_tune_epochs
history_fine = simple_model.fit(X_train_nn,Y_train,
epochs=total_epochs,
initial_epoch=history.epoch[-1],
validation_data=(X_val_nn,Y_val))
# In[130]:
acc += history_fine.history['accuracy']
val_acc += history_fine.history['val_accuracy']
loss += history_fine.history['loss']
val_loss += history_fine.history['val_loss']
# In[131]:
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.ylim([0.5, 1])
plt.plot([initial_epochs-1,initial_epochs-1],
plt.ylim(), label='Start Fine Tuning')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.ylim([0, 1.0])
plt.plot([initial_epochs-1,initial_epochs-1],
plt.ylim(), label='Start Fine Tuning')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()
# In[132]:
loss, accuracy = simple_model.evaluate(X_val_nn,Y_val)
print('Test accuracy :', accuracy)
# # Step 5. Convolutional Neural Networks (CNNs) classification
#
# Convolutional Neural Networks (CNNs): These are commonly used for image classification tasks and have been shown to be effective for tree species classification using Sentinel-2 imagery.
# In[32]:
CNNs_model = tf.keras.Sequential(
[
tf.keras.layers.Conv2D(64, (3,3), padding='same', activation="relu",input_shape=(kernel*kernel,bands,1)),
tf.keras.layers.MaxPooling2D((2, 2), strides=2),
tf.keras.layers.Conv2D(64, (3,3), padding='same', activation="relu"),
tf.keras.layers.MaxPooling2D((2, 2), strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation="relu"),
tf.keras.layers.Dense(16)
]
)
# In[33]:
CNNs_model.summary()
# In[34]:
CNNs_model.add(layers.Flatten())
CNNs_model.add(layers.Dense(64, activation='relu'))
CNNs_model.add(layers.Dense(output_size))
# In[35]:
CNNs_model.summary()
# In[36]:
CNNs_model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history2 = CNNs_model.fit(X_train_nn, Y_train, epochs=40,callbacks=[SelectiveProgbarLogger(verbose = 1,epoch_interval=20)], verbose=0,
validation_data=(X_val_nn, Y_val))
# In[37]:
y_pred_cnn_p = CNNs_model.predict(X_val_nn)
print("Prediction example: ", y_pred_cnn_p[0,:], " Class: ", np.argmax(y_pred_cnn_p[0,:]))
# In[38]:
y_pred_cnn = np.argmax(y_pred_cnn_p, axis=1)
ConfusionMatrixDisplay.from_predictions(Y_val, y_pred_cnn)
plt.show()
acc_dl = accuracy_score(Y_val, y_pred_cnn)
print("Accuracy Simple Deep Learning model: ", acc_dl)
# In[39]:
acc = history2.history['accuracy']
val_acc = history2.history['val_accuracy']
loss = history2.history['loss']
val_loss = history2.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()),1])
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0,1.0])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()
# # Step 6. - Residual Network: ResNet
#
# A residual neural network (ResNet) is an artificial neural network that imitate the pyramidal cells in the cerebral cortex. Particularly, the ResNet architecture consists of skip connections or shortcuts to jump over some layers. Typical ResNet models are implemented with double- or triple- layer skips that contain nonlinearities (ReLU) and batch normalization in between. These *cells* are known as *residual block*.
#
# ResNets connection weights are easier to optimize (especially for gradient descent-based optimizers) because the short cuts contribute to alleviate the vanishing gradient problem.
#
# In practice, the degradation problem (i.e., increasing the depth of a network leads to a decrease in its performance) is mitigated, and the observed performance (when the number of hidden layers increase) is much closer to the theoretical one.
# In[59]:
model_rn = tf.keras.applications.resnet50.ResNet50(
include_top=True,
weights=None,
input_tensor=None,
input_shape=( kernel*kernel,bands,1),
pooling=None,
classes=output_size)
model_rn.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# In[60]:
history3=model_rn.fit(X_train_nn, Y_train, epochs=100,callbacks=[SelectiveProgbarLogger(verbose = 1,epoch_interval=20)], verbose=0,validation_data=(X_val_nn, Y_val))
# In[61]:
y_pred_rn_p = model_rn.predict(X_val_nn)
y_pred_rn = np.argmax(y_pred_rn_p, axis=1)
##print(y_pred_rn)
#print(Y_val)
ConfusionMatrixDisplay.from_predictions(Y_val, y_pred_rn)
plt.show()
acc_rn = accuracy_score(Y_val, y_pred_rn)
print("Accuracy ResNet-50 model: ", acc_rn)
# In[62]:
acc = history3.history['accuracy']
val_acc = history3.history['val_accuracy']
loss = history3.history['loss']
val_loss = history3.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()),1])
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0,1.0])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()
# In[104]:
inputs = tf.keras.layers.Input(shape=(input_size[0], input_size[1],input_size[2]), name="input_image")
MobileNetV2_model = tf.keras.applications.MobileNetV2( input_tensor=inputs,
include_top=True,
input_shape=input_size,
weights=None,#'imagenet',
classes=output_size,
pooling=None)
# In[105]:
MobileNetV2_model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',#tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
MobileNetV2_model.summary()
# In[106]:
history4 = MobileNetV2_model.fit(X_train_nn3, Y_train, epochs=20,callbacks=[SelectiveProgbarLogger(verbose = 1,epoch_interval=5)], verbose=0,
validation_data=(X_val_nn3, Y_val))
# In[ ]:
y_pred_mbn_p = MobileNetV2_model.predict(X_val_nn3)
print("Prediction example: ", y_pred_mbn_p[0,:], " Class: ", np.argmax(y_pred_mbn_p[0,:]))
# In[90]:
y_pred_mbn = np.array(np.argmax(y_pred_mbn_p, axis=1)).astype(int)
ConfusionMatrixDisplay.from_predictions(Y_val, y_pred_mbn)
plt.show()
acc_dl = accuracy_score(Y_val, y_pred_mbn)
print("Accuracy Simple Deep Learning model: ", acc_dl)
# In[91]:
acc = history4.history['accuracy']
val_acc = history4.history['val_accuracy']
loss = history4.history['loss']
val_loss = history4.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()),1])
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0,1.0])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()
# # Step 7. Recurrent Neural Networks (RNNs) classification
#
# Recurrent Neural Networks (RNNs): RNNs can be used to analyze sequential data such as time series data, which can be useful for analyzing the temporal information present in Sentinel-2 imagery.
# In[40]:
batch_size = 64
# Each MNIST image batch is a tensor of shape (batch_size, 28, 28).
# Each input sequence will be of size (28, 28) (height is treated like time).
input_dim = 40
units = 64
# Build the RNN model
def build_model(allow_cudnn_kernel=True):
# CuDNN is only available at the layer level, and not at the cell level.
# This means `LSTM(units)` will use the CuDNN kernel,
# while RNN(LSTMCell(units)) will run on non-CuDNN kernel.
if allow_cudnn_kernel:
# The LSTM layer with default options uses CuDNN.
lstm_layer = keras.layers.LSTM(units, input_shape=(kernel*kernel, input_dim))
else:
# Wrapping a LSTMCell in a RNN layer will not use CuDNN.
lstm_layer = keras.layers.RNN(
keras.layers.LSTMCell(units), input_shape=(kernel*kernel, input_dim)
)
model = keras.models.Sequential(
[
lstm_layer,
keras.layers.BatchNormalization(),
keras.layers.Dense(output_size),
]
)
return model
# In[41]:
RNNs_model = build_model(allow_cudnn_kernel=True)
RNNs_model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="sgd",
metrics=["accuracy"],
)
history5=RNNs_model.fit(
X_train_nn, Y_train, epochs=100,callbacks=[SelectiveProgbarLogger(verbose = 1,epoch_interval=20)], verbose=0, validation_data=(X_val_nn, Y_val), batch_size=batch_size
)
# In[42]:
y_pred_rnn_p = RNNs_model.predict(X_val_nn)
print("Prediction example: ", y_pred_rnn_p[0,:], " Class: ", np.argmax(y_pred_rnn_p[0,:]))
# In[43]:
y_pred_rnn = np.argmax(y_pred_rnn_p, axis=1)
ConfusionMatrixDisplay.from_predictions(Y_val, y_pred_rnn)
plt.show()
acc_dl = accuracy_score(Y_val, y_pred_rnn)
print("Accuracy Simple Deep Learning model: ", acc_dl)
# In[44]:
acc = history5.history['accuracy']
val_acc = history5.history['val_accuracy']
loss = history5.history['loss']
val_loss = history5.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()),1])
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0,1.0])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()