-
Notifications
You must be signed in to change notification settings - Fork 1
/
hyperspectral_models.py
1487 lines (1193 loc) · 49 KB
/
hyperspectral_models.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module for hypesrspectral image classification with different models.
Available models are:
1 - `Deep Convolutional Neural Networks for Hyperspectral Image
Classification`
2 - `Hyperspectral Image Classification with Convolutional Neural
Networks`
3 - `LightGBM`
4 - `SVM with scikit learn SVC`
5 - `SVM with scikit learn LinearSVC`
6 - `RandomForestClassifier with scikit learn`
"""
from __future__ import division, absolute_import, print_function
import sys
import os
import errno
import scipy.io
import numpy as np
import math
import json
import timeit
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import keras
import lightgbm as lgb
from sklearn.model_selection import GridSearchCV
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
import joblib
from hyperspectral_preprocessing import preprocess_image
# Management of arguments
# =============================================================================
# Absolute path of the images directory
DATA_PATH = os.environ["HYPERSPECTRAL_DATA_PATH"]
# Name of the images information file
IMAGES_FILE_NAME = "images.json"
# Images information file
IMAGES_FILE = os.path.join(DATA_PATH, IMAGES_FILE_NAME)
# Absolute path of the working directory
WORKING_DIR = os.getcwd()
# Relative path of the output directory
OUTPUT_DIR = WORKING_DIR
# Name of the output file
OUTPUT_FILE_NAME = "output.txt"
# Output file
OUTPUT_FILE = os.path.join(OUTPUT_DIR, OUTPUT_FILE_NAME)
# Load random indexes
LOAD_INDEXES = False
INDEXES_DIR = None
# Available models
MODELS = {1: ("Deep Convolutional Neural Networks for Hyperspectral Image"
" Classification"),
2: ("Hyperspectral Image Classification with Convolutional Neural"
" Networks"),
3: "Lightgbm",
4: "SVM with scikit learn SVC",
5: "SVM with scikit learn LinearSVC",
6: "RandomForestClassifier with scikit learn"}
# Models variables
MODEL = 1
JOIN_MODELS = False
MODEL1 = 1
MODEL2 = 1
ALL_TOGETHER = False
# Load trained models
TRAINED_MODELS = False
TRAINED_MODELS_DIR = ""
TRAINED_MODELS_DIR2 = ""
TRAINED_MODELS_DIRS = []
# Default train epochs for CNN models
TRAIN_EPOCHS = 100
# Nuber of best features to use
FEATURES = 0
# Flag to activate lightgbm cross validation
CROSS_VALIDATION = False
# lightgbm cross validation parameters
N_ESTIMATORS_LIST = [100, 200, 400, 800]
#N_ESTIMATORS_LIST = [1000, 1200, 1400, 1800]
#N_ESTIMATORS_LIST = [1800, 1850, 1900, 1950, 2000]
#N_ESTIMATORS_LIST = [50, 100, 150, 200, 250,
# 300, 350, 400, 450, 500,
# 550, 600, 650, 700, 750,
# 800, 850, 900, 950, 1000,
# 1050, 1100, 1150, 1200, 1250,
# 1300, 1350, 1400, 1450, 1500,
# 1550, 1600, 1650, 1700, 1750,
# 1800, 1850, 1900, 1950, 2000]
MIN_CHILD_SAMPLES_LIST = [20, 50, 100, 200, 300]
def parse_args():
"""Analyzes the received parameters and returns them organized.
Takes the lis of string received at sys.argv and generates a
namespace asigning them to objects.
Returns
-------
out: namespace
The namespace with the values of the received parameters asigned
to objects.
"""
# Generate the parameter analyzer
parser = ArgumentParser(description = __doc__,
formatter_class = RawDescriptionHelpFormatter)
# Add arguments
parser.add_argument("--data_path",
help="Absolute path of the images.")
parser.add_argument("--working_dir",
help="Absolute path of the working directory.")
parser.add_argument("-d", "--output_dir",
help="Relative path of the output directory. "
+ "It will be added to the working directory.")
parser.add_argument("-o", "--output",
help="Name of the output file. ")
parser.add_argument("-i", "--indexes_dir",
help="Absolute path of random and train indexes "
+ "directory.")
parser.add_argument("-c", "--cross_validation",
action="store_true",
help="Flag to activate lightgbm cross validation.")
parser.add_argument("-e", "--train_epochs",
type=int,
help="Number of training epochs for CNN models.")
parser.add_argument("-f", "--features",
type=int,
help="Nuber of best features to use. If `0` (default) "
+ "it uses every feature.")
group1 = parser.add_mutually_exclusive_group()
group1.add_argument("-m", "--model",
type=int,
choices=MODELS.keys(),
help="Number corresponding to the selected model.")
group1.add_argument("-M", "--models",
nargs=2,
type=int,
choices=MODELS.keys(),
help="Number of the two models to combine.")
group2 = parser.add_mutually_exclusive_group()
group2.add_argument("-T", "--trained_models_dirs",
nargs=2,
help="Absolute path of trained models directories.")
group2.add_argument("-t", "--trained_models_dir",
help="Absolute path of trained models directory.")
group2.add_argument("-A", "--all_together",
nargs=4,
help="Absolute path of trained models directories.")
# Return the analized parameters
return parser.parse_args()
def use_args(args):
"""Realizes required actions depending on the received parameters.
Parameters
----------
args: namespace
The namespace with the values of the received parameters asigned
to objects.
"""
global DATA_PATH
global IMAGES_FILE
global WORKING_DIR
global OUTPUT_DIR
global OUTPUT_FILE_NAME
global OUTPUT_FILE
global LOAD_INDEXES
global INDEXES_DIR
global MODEL
global JOIN_MODELS
global MODEL1
global MODEL2
global ALL_TOGETHER
global TRAINED_MODELS
global TRAINED_MODELS_DIR
global TRAINED_MODELS_DIR2
global TRAINED_MODELS_DIRS
global CROSS_VALIDATION
global TRAIN_EPOCHS
global FEATURES
if args.data_path:
# Change the default path of the images
DATA_PATH = args.data_path
IMAGES_FILE = os.path.join(DATA_PATH, IMAGES_FILE_NAME)
if args.working_dir:
# Change the default path of the working directory
WORKING_DIR = args.working_dir
OUTPUT_DIR = WORKING_DIR
OUTPUT_FILE = os.path.join(OUTPUT_DIR, OUTPUT_FILE_NAME)
if args.output_dir:
# Change the default path of the output directory
OUTPUT_DIR = os.path.join(WORKING_DIR, args.output_dir)
OUTPUT_FILE = os.path.join(OUTPUT_DIR, OUTPUT_FILE_NAME)
if args.output:
# Change the default name of the output file
OUTPUT_FILE_NAME = args.output
OUTPUT_FILE = os.path.join(OUTPUT_DIR, OUTPUT_FILE_NAME)
if args.indexes_dir:
# Load random and train indexes from file
LOAD_INDEXES = True
INDEXES_DIR = args.indexes_dir
if args.model:
# Select model
MODEL = args.model
if args.models:
if not args.trained_models_dirs:
raise Exception("Arg. `-M --models` requires arg. "
+ "`-T --trained_models_dirs`")
# Models to combine
JOIN_MODELS = True
MODEL1 = args.models[0]
MODEL2 = args.models[1]
if args.trained_models_dir:
# Load trained models from file
TRAINED_MODELS = True
TRAINED_MODELS_DIR = args.trained_models_dir
if args.trained_models_dirs:
# Load trained models from file
TRAINED_MODELS = True
TRAINED_MODELS_DIR = args.trained_models_dirs[0]
TRAINED_MODELS_DIR2 = args.trained_models_dirs[1]
if args.all_together:
# The four models together
ALL_TOGETHER = True
TRAINED_MODELS_DIRS = args.all_together
if args.cross_validation:
# Activate cross_validation
CROSS_VALIDATION = True
if args.train_epochs:
# Change the default number of train epochs
TRAIN_EPOCHS = args.train_epochs
if args.features:
# Nuber of best features to use
FEATURES = args.features
# Preprocess functions
# =============================================================================
def model_1_parameters(num_features, num_classes, image_info):
"""Prepare the model training parameters.
Model from the paper `Deep Convolutional Neural Networks for
Hyperspectral Image Classification`.
"""
parameters = {}
parameters['n1'] = num_features
parameters['k1'] = int(math.floor(parameters['n1'] / 9))
parameters['n2'] = parameters['n1'] - parameters['k1'] + 1
if image_info['key'][:5] == "pavia":
parameters['n3'] = 30
parameters['k2'] = 3
else:
parameters['n3'] = 40
parameters['k2'] = 5
parameters['n4'] = 100
parameters['n5'] = num_classes
return parameters
def model_2_parameters(num_features, num_classes):
"""Prepare the model training parameters.
Model from the paper `Hyperspectral Image Classification with
Convolutional Neural Networks`.
"""
parameters = {}
parameters['num_features'] = num_features
parameters['num_classes'] = num_classes
return parameters
def model_3_parameters(num_features, num_classes, image_info):
"""Prepare the model training parameters.
Lightgbm model.
"""
parameters = {}
parameters['num_features'] = num_features
parameters['num_classes'] = num_classes
parameters['n_estimators'] = image_info['n_estimators']
min_child_samples = image_info['min_child_samples']
parameters['min_child_samples'] = min_child_samples
# Parameters message
with open(OUTPUT_FILE, 'a') as f:
f.write("min_child_samples: {}\n\n".format(min_child_samples))
return parameters
def model_4_parameters(num_features, num_classes, image_info):
"""Prepare the model training parameters.
SVM model.
"""
parameters = {}
parameters['num_features'] = num_features
parameters['num_classes'] = num_classes
if image_info['key'][:5] == "pavia":
parameters['C'] = 1.0
else:
parameters['C'] = 40.0
return parameters
def model_parameters(num_features, num_classes, image_info):
"""Prepare the model training parameters.
Chooses the parameters function depending on the selected model.
"""
if MODEL == 3:
return model_3_parameters(num_features, num_classes, image_info)
elif MODEL == 6:
return model_3_parameters(num_features, num_classes, image_info)
elif MODEL == 1:
return model_1_parameters(num_features, num_classes, image_info)
elif MODEL == 4:
return model_4_parameters(num_features, num_classes, image_info)
else:
# For models 2, and 5
return model_2_parameters(num_features, num_classes)
# Model generation functions
# =============================================================================
def get_model_1(parameters):
"""Generates the model.
Model from the paper `Deep Convolutional Neural Networks for
Hyperspectral Image Classification`.
See Section 3 `CNN-Based HSI Classification` in the paper for an
explanation about the structure and parameters.
Default range of `random_uniform` initializer: [-0.05, 0.05]
Default learning rate of `sgd` optimizer: 0.5
"""
# Parameters
n1 = parameters['n1']
k1 = parameters['k1']
n2 = parameters['n2']
n3 = parameters['n3']
k2 = parameters['k2']
n4 = parameters['n4']
n5 = parameters['n5']
NUM_FILTERS_C1 = 20
# Sequential model
model = keras.models.Sequential()
# Add C1 layer
# ------------
# Input_shape (batch, rows, cols, channels) = (-, n1, 1, 1)
# Output_shape (batch, rows, cols, channels) = (-, n2, 1, NUM_FILTERS_C1)
model.add(keras.layers.Conv2D(filters=NUM_FILTERS_C1,
kernel_size=(k1, 1),
padding='valid',
data_format="channels_last",
activation='tanh',
kernel_initializer='random_uniform',
bias_initializer='random_uniform',
input_shape=(n1,1,1)))
# Add M2 layer
# ------------
# Input_shape (batch, rows, cols, channels) = (-, n2, 1, NUM_FILTERS_C1)
# Output_shape (batch, rows, cols, channels) = (-, n3, 1, NUM_FILTERS_C1)
model.add(keras.layers.MaxPooling2D(pool_size=(k2, 1),
padding='same',
data_format="channels_last"))
# Flatten before dense layer
model.add(keras.layers.Flatten())
# Add F3 layer
# ------------
# Intput_shape (batch, rows, cols, channels) = (-, n3 x 1 x NUM_FILTERS_C1)
# Output_shape (batch, dim) = (-, n4)
model.add(keras.layers.Dense(units=n4,
activation='tanh',
kernel_initializer='random_uniform',
bias_initializer='random_uniform'))
# Add F4 layer
# ------------
# Intput_shape (batch, dim) = (1, n4)
# Output_shape (batch, dim) = (1, n5)
model.add(keras.layers.Dense(units=n5,
activation='softmax',
kernel_initializer='random_uniform',
bias_initializer='random_uniform'))
# Compile model
model.compile(optimizer='sgd',
loss='mean_squared_error',
metrics=['accuracy'])
# Print the model summary to output file
# To print to stdout: model.summary()
with open(OUTPUT_FILE, 'a') as f:
# Pass the file handle in as a lambda function to make it callable
model.summary(print_fn=lambda x: f.write(x + '\n'))
# Return the model
return model
def get_model_2(parameters):
"""Generates the model.
Model from the paper `Hyperspectral Image Classification with
Convolutional Neural Networks`.
"""
# Parameters
BANDS = parameters['num_features']
CLASSES = parameters['num_classes']
# Sequential model
model = keras.models.Sequential()
# Add convolution (1)
# -------------------
# Input_shape (batch, rows, cols, channels) = (-, 9, BANDS, 1)
# Output_shape (batch, rows, cols, channels) = (-, BANDS - 15, 1, 32)
model.add(keras.layers.Conv2D(filters=32,
kernel_size=(9, 16),
padding='same',
data_format="channels_last",
activation='tanh',
input_shape=(9, BANDS,1)))
# Add convolution (2)
# -------------------
# Input_shape (batch, rows, cols, channels) = (-, BANDS - 15, 1, 32)
# Output_shape (batch, rows, cols, channels) = (-, BANDS - 30, 1, 32)
model.add(keras.layers.Conv2D(filters=32,
kernel_size=(1, 16),
padding='same',
data_format="channels_last",
activation='tanh'))
# Add convolution (3)
# -------------------
# Input_shape (batch, rows, cols, channels) = (-, BANDS - 30, 1, 32)
# Output_shape (batch, rows, cols, channels) = (-, BANDS - 45, 1, 32)
model.add(keras.layers.Conv2D(filters=32,
kernel_size=(1, 16),
padding='same',
data_format="channels_last",
activation='tanh'))
# Flatten before dense layer
model.add(keras.layers.Flatten())
# Add fully connected (4)
# -----------------------
# Intput_shape (batch, rows, cols, channels) = (-, (BANDS - 45) x 1 x 32)
# Output_shape (batch, dim) = (-, 800)
model.add(keras.layers.Dense(units=800,
activation='tanh'))
# Add fully connected (5)
# -----------------------
# Intput_shape (batch, dim) = (-, 800)
# Output_shape (batch, dim) = (-, 800)
model.add(keras.layers.Dense(units=800,
activation='softmax'))
# Add fully connected to reduce to number of categories
# -----------------------------------------------------
# Intput_shape (batch, dim) = (-, 800)
# Output_shape (batch, dim) = (-, CLASSES)
model.add(keras.layers.Dense(units=CLASSES,
activation='softmax'))
# Compile model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Print the model summary to output file
# To print to stdout: model.summary()
with open(OUTPUT_FILE, 'a') as f:
# Pass the file handle in as a lambda function to make it callable
model.summary(print_fn=lambda x: f.write(x + '\n'))
# Return the model
return model
def get_model_3(parameters):
"""Generates the model.
Generates a lightgbm model.
"""
# Generate model
model = lgb.LGBMClassifier(
objective='multiclass',
class_weight='balanced',
n_estimators=parameters['n_estimators'],
min_child_samples=parameters['min_child_samples'])
# Return the model
return model
def get_cv_model_3(parameters):
"""Generates the cross validation model.
Generates a lightgbm cross validation model for each n_estimators in
N_ESTIMATORS_LIST.
"""
# Generate model
model = lgb.LGBMClassifier(objective='multiclass',
class_weight='balanced')
# Cross validation parameters
param_grid = {
'n_estimators': N_ESTIMATORS_LIST,
'min_child_samples' : MIN_CHILD_SAMPLES_LIST
}
# Grid search
cv_model = GridSearchCV(model, param_grid, cv=3)
# Return the models
return cv_model
def get_model_4(parameters):
"""Generates the model.
Generates a SVM model.
"""
# Generate model
model = svm.SVC(C=parameters['C'], gamma='scale', probability=True,
class_weight='balanced',
decision_function_shape='ovr')
# Return the model
return model
def get_model_5(parameters):
"""Generates the model.
Generates a SVM model.
"""
# Generate model
model = svm.LinearSVC(max_iter=100000)
# Return the model
return model
def get_model_6(parameters):
"""Generates the model.
Generates a RandomForestClassifier model.
"""
# Generate model
n_estimators = parameters['num_classes'] * parameters['n_estimators']
model = RandomForestClassifier(
class_weight='balanced',
n_estimators=n_estimators,
min_samples_split=parameters['min_child_samples'])
# Return the model
return model
def get_model(parameters):
"""Generates the model.
Chooses the generator depending on the selected model.
"""
if MODEL == 6:
return get_model_6(parameters)
elif MODEL == 5:
return get_model_5(parameters)
elif MODEL == 4:
return get_model_4(parameters)
elif MODEL == 3:
if CROSS_VALIDATION:
return get_cv_model_3(parameters)
else:
return get_model_3(parameters)
elif MODEL == 2:
return get_model_2(parameters)
else:
return get_model_1(parameters)
def load_keras_model(trained_models_dir, image_name):
"""Loads keras trained models."""
# Load the model
model_file = os.path.join(trained_models_dir,
"{}_model.h5py".format(image_name))
model = keras.models.load_model(model_file)
# Return the model
return model
def load_lgb_model(trained_models_dir, image_name):
"""Loads lightgbm trained models."""
# Load the model
model_file = os.path.join(trained_models_dir,
"{}_model.txt".format(image_name))
model = lgb.Booster(model_file=model_file)
# Return the model
return model
def load_joblib_model(trained_models_dir, image_name):
"""Loads scikit learn trained models."""
# Load the model
model_file = os.path.join(trained_models_dir,
"{}_model.joblib".format(image_name))
model = joblib.load(model_file)
# Return the model
return model
def load_model(model, trained_models_dir, image_name):
"""Loads the trained model."""
# if model == "keras":
if model == 1:
return load_keras_model(trained_models_dir, image_name)
# elif model == "lgb":
elif model == 3:
return load_lgb_model(trained_models_dir, image_name)
# elif model = "sklearn":
else:
return load_joblib_model(trained_models_dir, image_name)
def train_model_1(model, X_train, y_train, X_val, y_val, image_name):
"""Trains the model.
Model from the paper `Deep Convolutional Neural Networks for
Hyperspectral Image Classification`.
"""
# Train the model
batch_size = 50
start_time = timeit.default_timer()
history = model.fit(X_train,
y_train,
batch_size=batch_size,
epochs=TRAIN_EPOCHS,
verbose=1,
validation_data=(X_val, y_val))
end_time = timeit.default_timer()
time = end_time - start_time
with open(OUTPUT_FILE, 'a') as f:
f.write("\ntraining time: {:.3f}s\n".format(time))
# Save the model
model_file = os.path.join(OUTPUT_DIR, "{}_model.h5py".format(image_name))
model.save(model_file)
return model, history
def train_model_2(model, X_train, y_train, X_val, y_val, image_name):
"""Trains the model.
Model from the paper `Hyperspectral Image Classification with
Convolutional Neural Networks`.
"""
# Train the model
batch_size = 50
start_time = timeit.default_timer()
history = model.fit(X_train,
y_train,
batch_size=batch_size,
epochs=TRAIN_EPOCHS,
verbose=1,
validation_data=(X_val, y_val))
end_time = timeit.default_timer()
time = end_time - start_time
with open(OUTPUT_FILE, 'a') as f:
f.write("\ntraining time: {:.3f}s\n".format(time))
# Save the model
model_file = os.path.join(OUTPUT_DIR, "{}_model.h5py".format(image_name))
model.save(model_file)
return model, history
def train_model_3(model, X_train, y_train, X_val, y_val, image_name):
"""Trains the model.
Trains a lightgbm model.
"""
# Train the model
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=100)
# Save the model
model_file = os.path.join(OUTPUT_DIR, "{}_model.txt".format(image_name))
model.booster_.save_model(model_file)
return model, model
def train_cv_model_3(cv_model, X_train, y_train, X_val, y_val, image_name):
"""Trains the model.
Trains a lightgbm model for each n_estimators in N_ESTIMATORS_LIST.
"""
# Cross validation with train and validation sets
X_cv = np.append(X_train, X_val, axis=0)
y_cv = np.append(y_train, y_val, axis=0)
cv_model.fit(X_cv, y_cv)
# Write best parameters
with open(OUTPUT_FILE, 'a') as f:
f.write("\ncv_best_params: {}\n".format(cv_model.best_params_))
# Save the model
model_file = os.path.join(OUTPUT_DIR, "{}_cv_model.txt".format(image_name))
cv_model.best_estimator_.booster_.save_model(model_file)
return cv_model.best_estimator_, cv_model.best_estimator_
def train_model_4(model, X_train, y_train, image_name):
"""Trains the model.
Trains a SVM model.
"""
# Train the model
model.fit(X_train, y_train)
# Save the model
model_file = os.path.join(OUTPUT_DIR,
"{}_model.joblib".format(image_name))
joblib.dump(model, model_file)
return model, model
def train_model(model, X_train, y_train, X_val, y_val, image_name):
"""Trains the model.
Chooses the training function depending on the selected model.
"""
if MODEL == 1:
return train_model_1(model, X_train, y_train, X_val, y_val, image_name)
elif MODEL == 3:
if CROSS_VALIDATION:
return train_cv_model_3(model, X_train, y_train,
X_val, y_val, image_name)
else:
return train_model_3(model, X_train, y_train,
X_val, y_val, image_name)
elif MODEL == 2:
return train_model_2(model, X_train, y_train, X_val, y_val, image_name)
else:
# For models 4, 5 and 6
return train_model_4(model, X_train, y_train, image_name)
def plot_eval_1(trained_model, image_name):
"""Plots the training evaluation data of the model.
Model from the paper `Deep Convolutional Neural Networks for
Hyperspectral Image Classification`.
"""
# Get training evaluation data
train_accuracy = trained_model.history['acc']
train_val_accuracy = trained_model.history['val_acc']
train_loss = trained_model.history['loss']
train_val_loss = trained_model.history['val_loss']
# Generate accuracy plot
epochs = range(len(train_accuracy))
plt.figure()
plt.plot(epochs, train_accuracy, 'bo', label='Training accuracy')
plt.plot(epochs, train_val_accuracy, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
# Save accuracy plot
plot_file = os.path.join(OUTPUT_DIR,
"{}_training_accuracy".format(image_name))
plt.savefig(plot_file + ".svg", bbox_inches='tight', format='svg')
# Generate loss plot
plt.figure()
plt.plot(epochs, train_loss, 'bo', label='Training loss')
plt.plot(epochs, train_val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
# Save loss plot
plot_file = os.path.join(OUTPUT_DIR, "{}_training_loss".format(image_name))
plt.savefig(plot_file + ".svg", bbox_inches='tight', format='svg')
def plot_eval_2(trained_model, image_name):
"""Plots the training evaluation data of the model.
Model from the paper `Hyperspectral Image Classification with
Convolutional Neural Networks`.
"""
# Get training evaluation data
train_accuracy = trained_model.history['acc']
train_val_accuracy = trained_model.history['val_acc']
train_loss = trained_model.history['loss']
train_val_loss = trained_model.history['val_loss']
# Generate accuracy plot
epochs = range(len(train_accuracy))
plt.figure()
plt.plot(epochs, train_accuracy, 'bo', label='Training accuracy')
plt.plot(epochs, train_val_accuracy, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
# Save accuracy plot
plot_file = os.path.join(OUTPUT_DIR,
"{}_training_accuracy".format(image_name))
plt.savefig(plot_file + ".svg", bbox_inches='tight', format='svg')
# Generate loss plot
plt.figure()
plt.plot(epochs, train_loss, 'bo', label='Training loss')
plt.plot(epochs, train_val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
# Save loss plot
plot_file = os.path.join(OUTPUT_DIR, "{}_training_loss".format(image_name))
plt.savefig(plot_file + ".svg", bbox_inches='tight', format='svg')
def plot_eval_3(trained_model, X_val, y_val, image_name):
"""Plots the training evaluation data of the model.
Plots the training evaluation data of a lightgbm model.
"""
# FOR EACH CLASS
# val_pred = trained_model.predict_proba(X_val, num_iteration=iteration)
iterations = trained_model.booster_.current_iteration()
# results = np.zeros((2, iterations))
results = np.zeros((iterations,))
for pos in range(iterations):
# Calculate the current iteration (from 1 to iterations)
iteration = pos + 1
# Predict validation set for the current iteration
# start_time = timeit.default_timer()
val_pred = trained_model.predict(X_val, num_iteration=iteration)
# end_time = timeit.default_timer()
# time = end_time - start_time
# speed = int(X_val.shape[0] / time)
# Number of hits
val_ok = (val_pred == y_val)
# Percentage of hits
val_acc = val_ok.sum() / val_ok.size
# Actualize data for plotting results
# results[0][pos] = time
# results[1][pos] = val_acc
results[pos] = val_acc
# Generate accuracy plot
plt.figure()
# plt.plot(results[0], results[1], 'b')
plt.plot(results, 'b')
plt.title('Validation accuracy')
plt.xlabel('iterations')
plt.ylabel('accuracy')
plt.legend()
# Save validation plot
plot_file = os.path.join(OUTPUT_DIR, "{}_val_accuracy".format(image_name))
plt.savefig(plot_file + ".svg", bbox_inches='tight', format='svg')
def plot_eval_4(trained_model, X_val, y_val, image_name):
"""Plots the training evaluation data of the model.
Model from the paper `Hyperspectral Image Classification with
Convolutional Neural Networks`.
"""
# Predict with validation data
start_time = timeit.default_timer()
trained_model.predict(X_val)
end_time = timeit.default_timer()
time = end_time - start_time
speed = int(X_val.shape[0] / time)
# Get loss and accuracy
val_accuracy = trained_model.score(X_val, y_val)
# Prepare results messages
msg_time = "\nprediction time: {:.3f}s ({}px/s)\n".format(time, speed)
msg_val_acc = "val_accuracy: {:.3f}\n\n".format(val_accuracy)
# Write results messages
with open(OUTPUT_FILE, 'a') as f:
f.write(msg_time)
f.write(msg_val_acc)
def plot_eval(trained_model, X_val, y_val, image_name):
"""Plots the training evaluation data of the model.
Chooses the plot function depending on the selected model.
"""
if MODEL == 1:
return plot_eval_1(trained_model, image_name)
elif MODEL == 3:
if not CROSS_VALIDATION:
return plot_eval_3(trained_model, X_val, y_val, image_name)
elif MODEL == 2:
return plot_eval_2(trained_model, image_name)
else:
# For models 4, 5 and 6
return plot_eval_4(trained_model, X_val, y_val, image_name)
def predict_1(trained_model, X_test, y_test):
"""Predicts the test evaluation data of the model.
Model from the paper `Deep Convolutional Neural Networks for
Hyperspectral Image Classification`.
"""
# Predict with test data
start_time = timeit.default_timer()
test_prediction = trained_model.predict(X_test)
end_time = timeit.default_timer()
time = end_time - start_time
speed = int(X_test.shape[0] / time)
# Get loss and accuracy
test_loss, test_accuracy = trained_model.evaluate(X_test, y_test)
# Prepare results messages
msg_time = "prediction time: {:.3f}s ({}px/s)\n".format(time, speed)
msg_test_loss = "test_loss: {:.3f}\n".format(test_loss)
msg_test_acc = "test_accuracy: {:.3f}\n\n".format(test_accuracy)
# Write results messages
with open(OUTPUT_FILE, 'a') as f:
f.write(msg_time)
f.write(msg_test_loss)
f.write(msg_test_acc)
def predict_2(trained_model, X_test, y_test):
"""Predicts the test evaluation data of the model.