55
66from PIL import Image
77
8- from sklearn .svm import SVC
9- from sklearn .model_selection import train_test_split
10- from sklearn .metrics import classification_report , confusion_matrix , accuracy_score
8+ from ..training .ops import train_test_split
119
1210from tensorflow import keras
1311from keras .utils import np_utils
1917multiple = Multiple ()
2018
2119
20+ def accuracy_score (y_true , y_pred ):
21+ return np .mean (y_true == y_pred )
22+
23+
24+ def confusion_matrix (y_true , y_pred ):
25+ labels = np .unique (np .concatenate ((y_true , y_pred )))
26+ n_labels = len (labels )
27+ cm = np .zeros ((n_labels , n_labels ), dtype = int )
28+ label_to_idx = {label : i for i , label in enumerate (labels )}
29+ for t , p in zip (y_true , y_pred ):
30+ cm [label_to_idx [t ], label_to_idx [p ]] += 1
31+ return cm
32+
33+
34+ def classification_report (y_true , y_pred , target_names = None ):
35+ cm = confusion_matrix (y_true , y_pred )
36+ precision = np .diag (cm ) / np .sum (cm , axis = 0 )
37+ recall = np .diag (cm ) / np .sum (cm , axis = 1 )
38+ f1 = 2 * (precision * recall ) / (precision + recall )
39+ support = np .sum (cm , axis = 1 )
40+
41+ report = " precision recall f1-score support\n \n "
42+ for i , (p , r , f , s ) in enumerate (zip (precision , recall , f1 , support )):
43+ name = target_names [i ] if target_names and i < len (target_names ) else str (i )
44+ report += f"{ name :>12} { p :.2f} { r :.2f} { f :.2f} { s :>7} \n "
45+
46+ report += f"\n accuracy { accuracy_score (y_true , y_pred ):.2f} { np .sum (support ):>7} \n "
47+ return report
48+
49+
2250def load_dataset (dataset , shuffle = False ):
2351 """Load one of the available hyperspectral datasets (IP, PU, SA)."""
2452 paths , labels = [], []
@@ -220,31 +248,25 @@ def plot_train_history(history):
220248class HyperspectralModel :
221249 def __init__ (self , name , * args ):
222250 self .name = name
223- if self .name == 'svm' :
224- self .model = SVC (C = 150 , kernel = 'rbf' )
225- elif self .name == 'hsn' :
251+ if self .name == 'hsn' :
226252 self .input_shape , self .n_classes = args
227253 self .model = create_hsn_model (self .input_shape , self .n_classes ) # Hybrid Spectral Net
254+ else :
255+ raise ValueError (f"Model { name } not supported" )
228256
229257 def train (self , X , y , train_ratio = 0.7 , epochs = 50 ):
230- if self .name == 'svm' :
231- X_train , X_test , y_train , y_test = train_test_split (X .reshape (- 1 , X .shape [- 1 ]), y , train_size = train_ratio , stratify = y )
232- self .model .fit (X_train , y_train )
233- return y_test , self .model .predict (X_test )
234- elif self .name == 'hsn' :
258+ if self .name == 'hsn' :
235259 X = principal_components (X , n_components = self .input_shape [2 ])
236260 X_train , X_test , y_train , y_test = generate_training_data (X , y , self .input_shape [0 ], train_ratio )
237261 self .history = self .model .fit (x = X_train , y = np_utils .to_categorical (y_train ), batch_size = 256 , epochs = epochs )
238262 return y_test , np .argmax (self .model .predict (X_test ), axis = 1 )
239263
240264 def predict (self , X ):
241- if self .name == 'svm' :
242- return self .model .predict (X .reshape (- 1 , X .shape [2 ])).reshape (X .shape [0 ], X .shape [1 ])
243- elif self .name == 'hsn' :
265+ if self .name == 'hsn' :
244266 X = principal_components (X , n_components = self .input_shape [2 ])
245267 return predict_hsn_model (self .model , X , self .input_shape [0 ])
246268
247- def plot_history ():
269+ def plot_history (self ):
248270 if self .history :
249271 plot_train_history (self .history )
250272
@@ -256,5 +278,5 @@ def load(self, filename='model.h5'):
256278
257279
258280def create_model (name , * args ):
259- """Create a new model: svm or hsn"""
281+ """Create a new model: hsn"""
260282 return HyperspectralModel (name , * args )
0 commit comments