handeerdal commited on
Commit
4f1cc1f
·
verified ·
1 Parent(s): c30be90

Upload 8 files

Browse files
multiclass_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1495be9298e94badd3cce9fd585e0ea036044212207e863ce6eaeadd99d86794
3
+ size 579454
script.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+ import cv2
4
+ import pandas as pd
5
+ import numpy as np
6
+ from utils.utils import extract_features_from_image, perform_pca, train_svm_model
7
+
8
+
9
+ def run_inference(TEST_IMAGE_PATH, svm_model, k, SUBMISSION_CSV_SAVE_PATH):
10
+
11
+ test_images = os.listdir(TEST_IMAGE_PATH)
12
+ test_images.sort()
13
+
14
+ image_feature_list = []
15
+
16
+ for test_image in test_images:
17
+
18
+ path_to_image = os.path.join(TEST_IMAGE_PATH, test_image)
19
+
20
+ image = cv2.imread(path_to_image)
21
+ image_features = extract_features_from_image(image)
22
+
23
+ image_feature_list.append(image_features)
24
+
25
+ features_multiclass = np.array(image_feature_list)
26
+
27
+ features_multiclass_reduced = perform_pca(features_multiclass, k)
28
+
29
+ multiclass_predictions = svm_model.predict(features_multiclass_reduced)
30
+
31
+ df_predictions = pd.DataFrame(columns=["file_name", "category_id"])
32
+
33
+ for i in range(len(test_images)):
34
+ file_name = test_images[i]
35
+ new_row = pd.DataFrame({"file_name": file_name,
36
+ "category_id": multiclass_predictions[i]}, index=[0])
37
+ df_predictions = pd.concat([df_predictions, new_row], ignore_index=True)
38
+
39
+ df_predictions.to_csv(SUBMISSION_CSV_SAVE_PATH, index=False)
40
+
41
+
42
+
43
+
44
+ if __name__ == "__main__":
45
+
46
+ current_directory = os.path.dirname(os.path.abspath(__file__))
47
+ TEST_IMAGE_PATH = "/tmp/data/test_images"
48
+
49
+ MODEL_NAME = "multiclass_model.pkl"
50
+ MODEL_PATH = os.path.join(current_directory, MODEL_NAME)
51
+
52
+ k = 100
53
+ SUBMISSION_CSV_SAVE_PATH = os.path.join(current_directory, "submission.csv")
54
+
55
+ # load the model
56
+ with open(MODEL_PATH, 'rb') as file:
57
+ svm_model = pickle.load(file)
58
+
59
+
60
+ run_inference(TEST_IMAGE_PATH, svm_model, k, SUBMISSION_CSV_SAVE_PATH)
utils/__init__.py ADDED
File without changes
utils/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (174 Bytes). View file
 
utils/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (171 Bytes). View file
 
utils/__pycache__/utils.cpython-313.pyc ADDED
Binary file (8.37 kB). View file
 
utils/__pycache__/utils.cpython-39.pyc ADDED
Binary file (4.09 kB). View file
 
utils/utils.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from skimage.feature.texture import graycomatrix, graycoprops
4
+ from skimage.feature import local_binary_pattern, hog
5
+
6
+ from sklearn.svm import SVC
7
+ from sklearn.model_selection import train_test_split, GridSearchCV
8
+ from sklearn.metrics import accuracy_score, classification_report, precision_score, confusion_matrix
9
+ from sklearn.preprocessing import StandardScaler
10
+
11
+ def rgb_histogram(image, bins=256):
12
+ hist_features = []
13
+ for i in range(3):
14
+ hist, _ = np.histogram(image[:, :, i], bins=bins, range=(0, 256), density=True)
15
+ hist_features.append(hist)
16
+ return np.concatenate(hist_features)
17
+
18
+ def hu_moments(image):
19
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
20
+ moments = cv2.moments(gray)
21
+ hu_moments = cv2.HuMoments(moments).flatten()
22
+ return hu_moments
23
+
24
+ def glcm_features(image, distances=[1], angles=[0], levels=256, symmetric=True, normed=True):
25
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
26
+ glcm = graycomatrix(gray, distances=distances, angles=angles, levels=levels, symmetric=symmetric, normed=normed)
27
+ contrast = graycoprops(glcm, 'contrast').flatten()
28
+ dissimilarity = graycoprops(glcm, 'dissimilarity').flatten()
29
+ homogeneity = graycoprops(glcm, 'homogeneity').flatten()
30
+ energy = graycoprops(glcm, 'energy').flatten()
31
+ correlation = graycoprops(glcm, 'correlation').flatten()
32
+ asm = graycoprops(glcm, 'ASM').flatten()
33
+ return np.concatenate([contrast, dissimilarity, homogeneity, energy, correlation, asm])
34
+
35
+ def local_binary_pattern_features(image, P=8, R=1):
36
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
37
+ lbp = local_binary_pattern(gray, P, R, method='uniform')
38
+ (hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, P + 3), range=(0, P + 2), density=True)
39
+ return hist
40
+
41
+ def extract_features_from_image(image):
42
+ hist_features = rgb_histogram(image, bins=64)
43
+ hu_features = hu_moments(image)
44
+ glcm_features_vector = glcm_features(image)
45
+ lbp_features = local_binary_pattern_features(image)
46
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
47
+ hog_features = hog(
48
+ gray,
49
+ orientations=8,
50
+ pixels_per_cell=(32, 32),
51
+ cells_per_block=(2, 2),
52
+ visualize=False,
53
+ feature_vector=True
54
+ )
55
+ color_moments_features = []
56
+ for channel in cv2.split(image):
57
+ color_moments_features.append(np.mean(channel))
58
+ color_moments_features.append(np.std(channel))
59
+ color_moments_features = np.array(color_moments_features)
60
+ edges = cv2.Canny(gray, 50, 150)
61
+ edge_density = np.sum(edges > 0) / edges.size
62
+ edge_features = np.array([edge_density])
63
+ image_features = np.concatenate([
64
+ hist_features,
65
+ hu_features,
66
+ glcm_features_vector,
67
+ lbp_features,
68
+ hog_features,
69
+ color_moments_features,
70
+ edge_features
71
+ ])
72
+ return image_features
73
+
74
+ def perform_pca(data, num_components):
75
+ mean = np.mean(data, axis=0)
76
+ std_dev = np.std(data, axis=0)
77
+ data_standardized = (data - mean) / std_dev
78
+ covariance_matrix = np.cov(data_standardized, rowvar=False)
79
+ eigenvalues, eigenvectors = np.linalg.eig(covariance_matrix)
80
+ sorted_indices = np.argsort(eigenvalues)[::-1]
81
+ sorted_eigenvalues = eigenvalues[sorted_indices]
82
+ sorted_eigenvectors = eigenvectors[:, sorted_indices]
83
+ top_k_eigenvectors = sorted_eigenvectors[:, :num_components]
84
+ data_reduced = np.dot(data_standardized, top_k_eigenvectors)
85
+ data_reduced = np.real(data_reduced)
86
+ return data_reduced
87
+
88
+ def train_svm_model(features, labels, test_size=0.2, use_grid_search=False, use_precision_optimization=False):
89
+ if labels.ndim > 1 and labels.shape[1] > 1:
90
+ labels = np.argmax(labels, axis=1)
91
+ X_train, X_test, y_train, y_test = train_test_split(
92
+ features, labels, test_size=test_size, random_state=42,
93
+ stratify=labels
94
+ )
95
+ scaler = StandardScaler()
96
+ X_train_scaled = scaler.fit_transform(X_train)
97
+ X_test_scaled = scaler.transform(X_test)
98
+ if use_grid_search:
99
+ print("Grid Search...")
100
+ param_grid = {
101
+ 'C': [0.1, 1, 10, 100, 1000],
102
+ 'kernel': ['rbf', 'linear', 'poly'],
103
+ 'gamma': ['scale', 'auto', 0.001, 0.01, 0.1],
104
+ 'class_weight': ['balanced', None],
105
+ 'degree': [2, 3, 4]
106
+ }
107
+ svm = SVC(random_state=42, probability=True)
108
+ scoring = 'precision_weighted' if use_precision_optimization else 'accuracy'
109
+ grid_search = GridSearchCV(
110
+ svm, param_grid,
111
+ cv=5,
112
+ scoring=scoring,
113
+ n_jobs=-1,
114
+ verbose=1
115
+ )
116
+ grid_search.fit(X_train_scaled, y_train)
117
+ svm_model = grid_search.best_estimator_
118
+ print(f"\nbest params: {grid_search.best_params_}")
119
+ print(f" CV Score: {grid_search.best_score_:.4f}")
120
+ else:
121
+ svm_model = SVC(
122
+ kernel='rbf',
123
+ C=10,
124
+ gamma='scale',
125
+ class_weight='balanced',
126
+ random_state=42,
127
+ probability=True
128
+ )
129
+ svm_model.fit(X_train_scaled, y_train)
130
+ y_pred = svm_model.predict(X_test_scaled)
131
+ accuracy = accuracy_score(y_test, y_pred)
132
+ print(f'Test Accuracy: {accuracy:.2f}')
133
+ if use_precision_optimization:
134
+ precision_weighted = precision_score(y_test, y_pred, average='weighted', zero_division=0)
135
+ precision_macro = precision_score(y_test, y_pred, average='macro', zero_division=0)
136
+ print(f'Test Precision (Weighted): {precision_weighted:.4f}')
137
+ print(f'Test Precision (Macro): {precision_macro:.4f}')
138
+ print(f'\nClassification Report:')
139
+ print(classification_report(y_test, y_pred, zero_division=0))
140
+ results = {
141
+ 'model': svm_model,
142
+ 'scaler': scaler,
143
+ 'accuracy': accuracy,
144
+ 'precision_weighted': precision_weighted,
145
+ 'precision_macro': precision_macro,
146
+ 'y_test': y_test,
147
+ 'y_pred': y_pred
148
+ }
149
+ if use_grid_search:
150
+ results['best_params'] = grid_search.best_params_
151
+ results['cv_score'] = grid_search.best_score_
152
+ return svm_model, results
153
+ return svm_model