Newer
Older
import os
from sklearn.utils.class_weight import compute_class_weight
import numpy as np
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix, ConfusionMatrixDisplay, precision_score, f1_score, recall_score
from sklearn.utils.class_weight import compute_class_weight
import numpy as np
import sklearn
import matplotlib.pyplot as plt
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
main_directory = 'result_descriptors_and_labels/train'
data_matrix = np.empty((0, 128*nfeatures), dtype = np.float16)
label_vector = np.empty((0, 1), dtype = np.float16)
label_dict = {}
for npz_name in sorted(os.listdir(main_directory)):
npz_path = os.path.join(main_directory, npz_name)
npz_data = np.load(npz_path)
npz_arr = npz_data[list(npz_data.keys())[0]]
if npz_arr.shape[1] == 1:
label_vector = np.vstack((label_vector, npz_arr), dtype = np.float16)
else:
data_matrix = np.vstack((data_matrix, npz_arr), dtype = np.float16)
label_dict[npz_arr[0,0]] = npz_name[:npz_name.find('_label_')]
print("Hier1")
num_classes = len(np.unique(label_vector))
class_weights = compute_class_weight('balanced', classes=np.unique(label_vector), y=label_vector.flatten())
class_weights_dict = dict(zip(np.unique(label_vector), class_weights))
print("Hier2")
#class_weights = dict(zip(list(range(len(os.listdir(main_directory))/2)), compute_class_weight('balanced', list(range(len(os.listdir(main_directory))/2)), label_vector)))
plant_diseases_svm = SVC(kernel='linear', class_weight=class_weights_dict)
plant_diseases_svm.fit(data_matrix, np.ravel(label_vector))
print("Hier3")
test_directory = 'result_descriptors_and_labels/test'
test_data_matrix = np.empty((0, 128*nfeatures), dtype = np.float16)
test_label_vector = np.empty((0,1), dtype = np.float16)
for npz_name in sorted(os.listdir(test_directory)):
npz_path = os.path.join(test_directory, npz_name)
npz_data = np.load(npz_path)
npz_arr = npz_data[list(npz_data.keys())[0]]
if npz_arr.shape[1] == 1:
test_label_vector = np.vstack((label_vector, npz_arr),dtype = np.float16)
else:
test_data_matrix = np.vstack((data_matrix, npz_arr),dtype = np.float16)
test_classes = plant_diseases_svm.predict(test_data_matrix)
accuracy = accuracy_score(test_label_vector, test_classes)
ps = precision_score(test_label_vector, test_classes, average=None)
f1 = f1_score(test_label_vector, test_classes, average=None)
rc = recall_score(test_label_vector, test_classes, average=None)