annaferrari02 commited on
Commit
7b4617a
·
verified ·
1 Parent(s): 1a0ffa3

upload files for model

Browse files
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ---
2
+ license: mit
3
+ ---
multiclass_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac42a32dd5498c71ef249f31d2e7c42aa7eb2a2ef424c80231a6f3240a901e3f
3
+ size 3596894
pca_params.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f652e3a80b3914b927b866fbd862225c12cbbde0bb61b52789f49113b0e5d8f7
3
+ size 95215926
script.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script
3
+ Version combining baseline structure with enhanced features
4
+ """
5
+
6
+ import os
7
+ import pickle
8
+ import cv2
9
+ import pandas as pd
10
+ import numpy as np
11
+ from utils.utils import extract_features_from_image, apply_pca_transform
12
+
13
+
14
+ def run_inference(TEST_IMAGE_PATH, svm_model, pca_params, SUBMISSION_CSV_SAVE_PATH):
15
+ """
16
+ Run inference on test images
17
+
18
+ Args:
19
+ TEST_IMAGE_PATH: Path to test images (/tmp/data/test_images)
20
+ svm_model: Trained SVM model
21
+ pca_params: Dictionary containing PCA transformation parameters
22
+ SUBMISSION_CSV_SAVE_PATH: Path to save submission.csv
23
+ """
24
+
25
+ # Load test images
26
+ test_images = os.listdir(TEST_IMAGE_PATH)
27
+ test_images.sort()
28
+
29
+ # Extract features from all test images
30
+ image_feature_list = []
31
+
32
+ for test_image in test_images:
33
+ path_to_image = os.path.join(TEST_IMAGE_PATH, test_image)
34
+
35
+ image = cv2.imread(path_to_image)
36
+
37
+ # Extract features (using enhanced features by default)
38
+ image_features = extract_features_from_image(image)
39
+
40
+ image_feature_list.append(image_features)
41
+
42
+ features_array = np.array(image_feature_list)
43
+
44
+ # Apply PCA transformation using saved parameters
45
+ features_reduced = apply_pca_transform(features_array, pca_params)
46
+
47
+ # Run predictions
48
+ predictions = svm_model.predict(features_reduced)
49
+
50
+ # Create submission CSV
51
+ df_predictions = pd.DataFrame({
52
+ "file_name": test_images,
53
+ "category_id": predictions
54
+ })
55
+
56
+ df_predictions.to_csv(SUBMISSION_CSV_SAVE_PATH, index=False)
57
+
58
+
59
+ if __name__ == "__main__":
60
+
61
+ # Paths
62
+ current_directory = os.path.dirname(os.path.abspath(__file__))
63
+ TEST_IMAGE_PATH = "/tmp/data/test_images"
64
+
65
+ MODEL_NAME = "multiclass_model.pkl"
66
+ MODEL_PATH = os.path.join(current_directory, MODEL_NAME)
67
+
68
+ PCA_PARAMS_NAME = "pca_params.pkl"
69
+ PCA_PARAMS_PATH = os.path.join(current_directory, PCA_PARAMS_NAME)
70
+
71
+ SUBMISSION_CSV_SAVE_PATH = os.path.join(current_directory, "submission.csv")
72
+
73
+ # Load trained SVM model
74
+ with open(MODEL_PATH, 'rb') as file:
75
+ svm_model = pickle.load(file)
76
+
77
+ # Load PCA parameters
78
+ with open(PCA_PARAMS_PATH, 'rb') as file:
79
+ pca_params = pickle.load(file)
80
+
81
+ # Run inference
82
+ run_inference(TEST_IMAGE_PATH, svm_model, pca_params, SUBMISSION_CSV_SAVE_PATH)
train.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training script for surgical instrument classification
3
+ """
4
+
5
+ import os
6
+ import pickle
7
+ import cv2
8
+ import pandas as pd
9
+ import numpy as np
10
+ from utils.utils import extract_features_from_image, fit_pca_transformer, train_svm_model, augment_image
11
+ from utils.utils import extract_features_from_image, fit_pca_transformer, augment_image
12
+ from sklearn.model_selection import GridSearchCV, train_test_split
13
+ from sklearn.svm import SVC
14
+ from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report
15
+
16
+ def train_and_save_model(base_path, images_folder, gt_csv, save_dir, n_components=100):
17
+ """
18
+ Complete training pipeline that saves everything needed for submission
19
+
20
+ Args:
21
+ base_path: Base directory path
22
+ images_folder: Folder name containing images
23
+ gt_csv: Ground truth CSV filename
24
+ save_dir: Directory to save model artifacts
25
+ n_components: Number of PCA components
26
+ """
27
+
28
+ print("="*80)
29
+ print("TRAINING SURGICAL INSTRUMENT CLASSIFIER")
30
+ print("="*80)
31
+
32
+ # Setup paths
33
+ PATH_TO_GT = os.path.join(base_path, gt_csv)
34
+ PATH_TO_IMAGES = os.path.join(base_path, images_folder)
35
+
36
+ print(f"\nConfiguration:")
37
+ print(f" Ground Truth: {PATH_TO_GT}")
38
+ print(f" Images: {PATH_TO_IMAGES}")
39
+ print(f" PCA Components: {n_components}")
40
+ print(f" Save directory: {save_dir}")
41
+
42
+ # Load ground truth
43
+ df = pd.read_csv(PATH_TO_GT)
44
+ print(f"\nLoaded {len(df)} training samples")
45
+ print(f"\nLabel distribution:")
46
+ print(df['category_id'].value_counts().sort_index())
47
+
48
+ # Extract features
49
+ print(f"\n{'='*80}")
50
+ print("STEP 1: FEATURE EXTRACTION WITH AUGMENTATION")
51
+ print("="*80)
52
+
53
+ # Augmentation configuration
54
+ AUGMENTATIONS_PER_IMAGE = 2 # Conservative: 3x total dataset
55
+
56
+ print(f"\nAugmentation settings:")
57
+ print(f" Augmentations per image: {AUGMENTATIONS_PER_IMAGE}")
58
+ print(f" Rotation range: -10° to +10°")
59
+ print(f" Brightness range: 0.9 to 1.1")
60
+ print(f" Horizontal flip: Yes")
61
+ print(f" Gaussian noise: σ=3")
62
+ print(f" Expected total samples: {len(df) * (1 + AUGMENTATIONS_PER_IMAGE)}")
63
+
64
+ features = []
65
+ labels = []
66
+
67
+ for i in range(len(df)):
68
+ if i % 500 == 0:
69
+ print(f" Processing {i}/{len(df)* (1 + AUGMENTATIONS_PER_IMAGE)}...")
70
+
71
+ image_name = df.iloc[i]["file_name"]
72
+ label = df.iloc[i]["category_id"]
73
+
74
+ path_to_image = os.path.join(PATH_TO_IMAGES, image_name)
75
+
76
+ try:
77
+ image = cv2.imread(path_to_image)
78
+ if image is None:
79
+ print(f" Warning: Could not read {image_name}, skipping...")
80
+ continue
81
+
82
+ # ORIGINAL IMAGE
83
+ original_features = extract_features_from_image(image)
84
+ features.append(original_features)
85
+ labels.append(label)
86
+
87
+ # AUGMENTED VERSIONS
88
+ for aug_idx in range(AUGMENTATIONS_PER_IMAGE):
89
+ # Generate augmented image
90
+ aug_image = augment_image(
91
+ image,
92
+ rotation_range=(-10, 10),
93
+ brightness_range=(0.9, 1.1),
94
+ add_noise=True,
95
+ noise_sigma=3,
96
+ horizontal_flip=(aug_idx == 0) # Only flip on first augmentation
97
+ )
98
+
99
+ # Extract features from augmented image
100
+ aug_features = extract_features_from_image(aug_image)
101
+ features.append(aug_features)
102
+ labels.append(label)
103
+
104
+ except Exception as e:
105
+ print(f" Error processing {image_name}: {e}")
106
+ continue
107
+
108
+ features_array = np.array(features)
109
+ labels_array = np.array(labels)
110
+
111
+ print(f"\nFeature extraction complete!")
112
+ print(f" Original samples: {len(df)}")
113
+ print(f" Total samples (with augmentation): {len(features)}")
114
+ print(f" Features shape: {features_array.shape}")
115
+ print(f" Labels shape: {labels_array.shape}")
116
+ print(f" Feature dimension: {features_array.shape[1]}")
117
+
118
+ # Apply PCA
119
+ print(f"\n{'='*80}")
120
+ print("STEP 2: DIMENSIONALITY REDUCTION (PCA)")
121
+ print("="*80)
122
+
123
+ pca_params, features_reduced = fit_pca_transformer(features_array, n_components)
124
+
125
+ print(f" Reduced from {features_array.shape[1]} to {n_components} dimensions")
126
+ print(f" Explained variance: {pca_params['cumulative_variance'][-1]:.4f}")
127
+
128
+ # Train SVM with Grid Search
129
+ print(f"\n{'='*80}")
130
+ print("STEP 3: TRAINING SVM CLASSIFIER WITH GRID SEARCH")
131
+ print("="*80)
132
+
133
+ # Split data for training and testing
134
+ X_train, X_test, y_train, y_test = train_test_split(
135
+ features_reduced,
136
+ labels_array,
137
+ test_size=0.2,
138
+ random_state=42,
139
+ stratify=labels_array
140
+ )
141
+
142
+ print(f"\nData split:")
143
+ print(f" Training samples: {len(X_train)}")
144
+ print(f" Test samples: {len(X_test)}")
145
+
146
+ # Define parameter grid
147
+ param_grid = {
148
+ 'C': [1, 10, 50, 100],
149
+ 'gamma': ['scale', 0.001, 0.01, 0.1],
150
+ 'kernel': ['rbf']
151
+ }
152
+
153
+ print(f"\nGrid Search parameters:")
154
+ print(f" C values: {param_grid['C']}")
155
+ print(f" Gamma values: {param_grid['gamma']}")
156
+ print(f" Kernel: {param_grid['kernel']}")
157
+ print(f" Total combinations: {len(param_grid['C']) * len(param_grid['gamma'])}")
158
+ print(f" Cross-validation folds: 3")
159
+ print(f"\nThis will take 15-30 minutes...")
160
+
161
+ # Perform Grid Search
162
+ grid_search = GridSearchCV(
163
+ SVC(),
164
+ param_grid,
165
+ cv=3,
166
+ scoring='f1_macro',
167
+ n_jobs=-1,
168
+ verbose=2
169
+ )
170
+
171
+ print("\nStarting Grid Search...")
172
+ grid_search.fit(X_train, y_train)
173
+
174
+ # Get best model
175
+ svm_model = grid_search.best_estimator_
176
+
177
+ print(f"\n{'='*80}")
178
+ print("GRID SEARCH COMPLETE!")
179
+ print("="*80)
180
+ print(f"\nBest parameters found:")
181
+ print(f" C: {grid_search.best_params_['C']}")
182
+ print(f" Gamma: {grid_search.best_params_['gamma']}")
183
+ print(f" Kernel: {grid_search.best_params_['kernel']}")
184
+ print(f"\nBest cross-validation F1-score: {grid_search.best_score_:.4f}")
185
+
186
+ # Train final model and evaluate
187
+ print(f"\n{'='*80}")
188
+ print("FINAL MODEL EVALUATION")
189
+ print("="*80)
190
+
191
+ # Training set performance
192
+ y_train_pred = svm_model.predict(X_train)
193
+ train_accuracy = accuracy_score(y_train, y_train_pred)
194
+ train_f1 = f1_score(y_train, y_train_pred, average='macro')
195
+ train_precision = precision_score(y_train, y_train_pred, average='macro')
196
+ train_recall = recall_score(y_train, y_train_pred, average='macro')
197
+
198
+ # Test set performance
199
+ y_test_pred = svm_model.predict(X_test)
200
+ test_accuracy = accuracy_score(y_test, y_test_pred)
201
+ test_f1 = f1_score(y_test, y_test_pred, average='macro')
202
+ test_precision = precision_score(y_test, y_test_pred, average='macro')
203
+ test_recall = recall_score(y_test, y_test_pred, average='macro')
204
+
205
+ print(f"\nTraining Set Performance:")
206
+ print(f" Accuracy: {train_accuracy:.4f}")
207
+ print(f" Precision: {train_precision:.4f}")
208
+ print(f" Recall: {train_recall:.4f}")
209
+ print(f" F1-score: {train_f1:.4f}")
210
+
211
+ print(f"\nTest Set Performance:")
212
+ print(f" Accuracy: {test_accuracy:.4f}")
213
+ print(f" Precision: {test_precision:.4f}")
214
+ print(f" Recall: {test_recall:.4f}")
215
+ print(f" F1-score: {test_f1:.4f}")
216
+
217
+ print(f"\nDetailed Classification Report:")
218
+ print(classification_report(y_test, y_test_pred,
219
+ target_names=[f'Class {i}' for i in sorted(np.unique(labels_array))]))
220
+
221
+ print(f"\nModel Details:")
222
+ print(f" Support vectors: {len(svm_model.support_)}")
223
+ print(f" Support vectors per class: {svm_model.n_support_}")
224
+
225
+ # Save SVM model
226
+ model_path = os.path.join(save_dir, "multiclass_model.pkl")
227
+ with open(model_path, "wb") as f:
228
+ pickle.dump(svm_model, f)
229
+ print(f" ✓ Saved SVM model: {model_path}")
230
+
231
+ # Save PCA parameters
232
+ pca_path = os.path.join(save_dir, "pca_params.pkl")
233
+ with open(pca_path, "wb") as f:
234
+ pickle.dump(pca_params, f)
235
+ print(f" ✓ Saved PCA params: {pca_path}")
236
+
237
+
238
+ print(f"\n{'='*80}")
239
+ print("TRAINING COMPLETE!")
240
+ print("="*80)
241
+ print(f"\nFinal Optimized Results:")
242
+ print(f" Best Parameters: C={grid_search.best_params_['C']}, gamma={grid_search.best_params_['gamma']}")
243
+ print(f" CV F1-score: {grid_search.best_score_:.4f}")
244
+ print(f" Test F1-score: {test_f1:.4f}")
245
+ print(f" Test Precision: {test_precision:.4f}")
246
+ print(f" Test Recall: {test_recall:.4f}")
247
+ print(f"\nFiles saved to: {save_dir}")
248
+ print(f"\nNext steps:")
249
+ print(f" 1. Create a 'utils' folder in your HuggingFace repository")
250
+ print(f" 2. Copy utils.py into the 'utils' folder")
251
+ print(f" 3. Copy script.py, multiclass_model.pkl, and pca_params.pkl to the repository root")
252
+ print(f" 4. Create an empty __init__.py file in the 'utils' folder")
253
+ print(f" 5. Submit to competition!")
254
+
255
+
256
+ if __name__ == "__main__":
257
+
258
+ BASE_PATH = "C:/Users/anna2/ISM/ANNA/phase1a-data-augmentation"
259
+ IMAGES_FOLDER = "C:/Users/anna2/ISM/Images"
260
+ GT_CSV = "C:/Users/anna2/ISM/Baselines/phase_1a/gt_for_classification_multiclass_from_filenames_0_index.csv"
261
+
262
+ SAVE_DIR = "C:/Users/anna2/ISM/ANNA/phase1a-data-augmentation"
263
+
264
+ # Number of PCA components
265
+ N_COMPONENTS = 250 #can be adjusted
266
+
267
+ # Train and save
268
+ train_and_save_model(BASE_PATH, IMAGES_FOLDER, GT_CSV, SAVE_DIR, N_COMPONENTS)
utils/__pycache__/utils.cpython-312.pyc ADDED
Binary file (13.4 kB). View file
 
utils/utils.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for surgical instrument classification
3
+ """
4
+
5
+ import cv2
6
+ import numpy as np
7
+ from skimage.feature.texture import graycomatrix, graycoprops
8
+ from skimage.feature import local_binary_pattern, hog
9
+ from sklearn.decomposition import PCA
10
+ from sklearn.svm import SVC
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.metrics import accuracy_score, f1_score
13
+
14
+ def augment_image(image, rotation_range=(-10, 10), brightness_range=(0.9, 1.1),
15
+ add_noise=True, noise_sigma=3, horizontal_flip=False):
16
+ """
17
+ Apply safe augmentations for surgical instrument images
18
+
19
+ Args:
20
+ image: Input image (BGR format from cv2)
21
+ rotation_range: (min, max) rotation in degrees
22
+ brightness_range: (min, max) brightness multiplier
23
+ add_noise: Whether to add Gaussian noise
24
+ noise_sigma: Standard deviation of Gaussian noise
25
+ horizontal_flip: Whether to flip horizontally
26
+
27
+ Returns:
28
+ Augmented image
29
+ """
30
+ img = image.copy()
31
+
32
+ # 1. Random rotation
33
+ if rotation_range:
34
+ angle = np.random.uniform(rotation_range[0], rotation_range[1])
35
+ h, w = img.shape[:2]
36
+ center = (w // 2, h // 2)
37
+ M = cv2.getRotationMatrix2D(center, angle, 1.0)
38
+ img = cv2.warpAffine(img, M, (w, h), borderMode=cv2.BORDER_REFLECT)
39
+
40
+ # 2. Random brightness adjustment
41
+ if brightness_range:
42
+ alpha = np.random.uniform(brightness_range[0], brightness_range[1])
43
+ img = cv2.convertScaleAbs(img, alpha=alpha, beta=0)
44
+
45
+ # 3. Horizontal flip
46
+ if horizontal_flip:
47
+ img = cv2.flip(img, 1)
48
+
49
+ # 4. Add Gaussian noise
50
+ if add_noise:
51
+ noise = np.random.normal(0, noise_sigma, img.shape)
52
+ img = np.clip(img.astype(np.float32) + noise, 0, 255).astype(np.uint8)
53
+
54
+ return img
55
+
56
+
57
+ def preprocess_image(image):
58
+ """
59
+ Apply CLAHE preprocessing for better contrast
60
+ MUST be defined BEFORE extract_features_from_image
61
+ (Contrast Limited Adaptive Historam Equalization)
62
+ """
63
+ # Convert to LAB color space (basically separating lightness, L, from color info)
64
+ lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
65
+ l, a, b = cv2.split(lab) #this enhances constrast between colors
66
+
67
+ # Apply CLAHE to L channel
68
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) #split into a 8x8 grid and performs the contrast enhancement to the smaller regions instead of full image
69
+ l = clahe.apply(l)
70
+
71
+ # Merge and convert back
72
+ enhanced = cv2.merge([l, a, b]) #merge the contrast channel with the other two (A,B)
73
+ enhanced = cv2.cvtColor(enhanced, cv2.COLOR_LAB2BGR) #go back to BGR so it can be used later on
74
+
75
+ return enhanced
76
+
77
+
78
+ #this is the same as baseline code, well working so let's keep it
79
+ #it basically computes normalized color histograms for the classic three channels
80
+ def rgb_histogram(image, bins=256):
81
+ """Extract RGB histogram features"""
82
+ hist_features = []
83
+ for i in range(3): # RGB Channels
84
+ hist, _ = np.histogram(image[:, :, i], bins=bins, range=(0, 256), density=True)
85
+ hist_features.append(hist)
86
+ return np.concatenate(hist_features)
87
+
88
+
89
+ def hu_moments(image):
90
+ """Extract Hu moment features, takes BGR format in input
91
+ basically provides shape description that are consistent
92
+ wrt to position, size and rotation"""
93
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #turn to greyscale (works in 1 channel)
94
+ moments = cv2.moments(gray)
95
+ hu_moments = cv2.HuMoments(moments).flatten()
96
+ return hu_moments
97
+
98
+
99
+ def glcm_features(image, distances=[1], angles=[0], levels=256, symmetric=True, normed=True):
100
+ """Extract GLCM texture features,
101
+ captures texture info considering spatial
102
+ relationship between pixel intensities. works well with RGB and hu"""
103
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
104
+ glcm = graycomatrix(gray, distances=distances, angles=angles, levels=levels,
105
+ symmetric=symmetric, normed=normed)
106
+ contrast = graycoprops(glcm, 'contrast').flatten()
107
+ dissimilarity = graycoprops(glcm, 'dissimilarity').flatten()
108
+ homogeneity = graycoprops(glcm, 'homogeneity').flatten()
109
+ energy = graycoprops(glcm, 'energy').flatten()
110
+ correlation = graycoprops(glcm, 'correlation').flatten()
111
+ asm = graycoprops(glcm, 'ASM').flatten()
112
+ return np.concatenate([contrast, dissimilarity, homogeneity, energy, correlation, asm])
113
+
114
+
115
+ def local_binary_pattern_features(image, P=8, R=1):
116
+ """Extract Local Binary Pattern features, useful for light changes
117
+ combined with rgb, hu and glcm"""
118
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
119
+ lbp = local_binary_pattern(gray, P, R, method='uniform')
120
+ (hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, P + 3),
121
+ range=(0, P + 2), density=True)
122
+ return hist #feature vector representing the texture of the image
123
+
124
+
125
+ def hog_features(image, orientations=12, pixels_per_cell=(8, 8), cells_per_block=(2, 2)):
126
+ """
127
+ Extract HOG (Histogram of Oriented Gradients) features
128
+ Great for capturing shape and edge information in surgical instruments
129
+ """
130
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
131
+
132
+ # Resize to standard size for consistency
133
+ gray_resized = cv2.resize(gray, (256, 256))
134
+
135
+ hog_features_vector = hog(
136
+ gray_resized,
137
+ orientations=orientations,
138
+ pixels_per_cell=pixels_per_cell,
139
+ cells_per_block=cells_per_block,
140
+ block_norm='L2-Hys',
141
+ feature_vector=True
142
+ )
143
+
144
+ return hog_features_vector #Returns a vector capturing local edge
145
+ #directions and shape information, useful for detecting instruments,
146
+ #objects, or structural patterns.
147
+
148
+
149
+ def luv_histogram(image, bins=32): #instead of bgr it uses lightness and chromatic components
150
+ """
151
+ Extract histogram in LUV color space
152
+ LUV is perceptually uniform and better for underwater/surgical imaging
153
+ """
154
+ luv = cv2.cvtColor(image, cv2.COLOR_BGR2LUV)
155
+ hist_features = []
156
+ for i in range(3):
157
+ hist, _ = np.histogram(luv[:, :, i], bins=bins, range=(0, 256), density=True)
158
+ hist_features.append(hist)
159
+ return np.concatenate(hist_features)
160
+
161
+
162
+ def gabor_features(image, frequencies=[0.1, 0.2, 0.3],
163
+ orientations=[0, 45, 90, 135]):
164
+ """
165
+ Extract Gabor filter features (gabor kernels)
166
+ texture orientation that deals well with different scales and diff orientation
167
+ """
168
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # uses intensity and not color
169
+ features = []
170
+
171
+ for freq in frequencies:
172
+ for theta in orientations:
173
+ theta_rad = theta * np.pi / 180
174
+ kernel = cv2.getGaborKernel((21, 21), 5, theta_rad,
175
+ 10.0/freq, 0.5, 0)
176
+ filtered = cv2.filter2D(gray, cv2.CV_32F, kernel)
177
+ features.append(np.mean(filtered))
178
+ features.append(np.std(filtered))
179
+
180
+ return np.array(features)
181
+
182
+
183
+ def extract_features_from_image(image):
184
+ """
185
+ Extract enhanced features from image
186
+ Uses baseline features + HOG + LUV histogram + Gabor for better performance
187
+
188
+ Args:
189
+ image: Input image (BGR format from cv2.imread)
190
+
191
+ Returns:
192
+ Feature vector as numpy array
193
+ """
194
+ # Preprocess image first
195
+ image = preprocess_image(image)
196
+
197
+ # Baseline features
198
+ hist_features = rgb_histogram(image)
199
+ hu_features = hu_moments(image)
200
+ glcm_features_vector = glcm_features(image)
201
+ lbp_features = local_binary_pattern_features(image)
202
+
203
+ # Enhanced features that add discriminative power for complex images
204
+ hog_feat = hog_features(image)
205
+ luv_hist = luv_histogram(image)
206
+ gabor_feat = gabor_features(image)
207
+
208
+ # Concatenate all features (produces a single vector)
209
+ image_features = np.concatenate([
210
+ hist_features,
211
+ hu_features,
212
+ glcm_features_vector,
213
+ lbp_features,
214
+ hog_feat,
215
+ luv_hist,
216
+ gabor_feat
217
+ ])
218
+
219
+ return image_features # comprehensive numerical representation of the imag
220
+
221
+
222
+ def fit_pca_transformer(data, num_components):
223
+ """
224
+ Fit a PCA transformer on training data
225
+
226
+ Args:
227
+ data: Training data (n_samples, n_features)
228
+ num_components: Number of PCA components to keep
229
+
230
+ Returns:
231
+ pca_params: Dictionary containing PCA parameters
232
+ data_reduced: PCA-transformed data
233
+ """
234
+
235
+ # Standardize the data
236
+ mean = np.mean(data, axis=0)
237
+ std = np.std(data, axis=0)
238
+
239
+ # Avoid division by zero
240
+ std[std == 0] = 1.0
241
+
242
+ data_standardized = (data - mean) / std
243
+
244
+ # Fit PCA using sklearn
245
+ pca_model = PCA(n_components=num_components)
246
+ data_reduced = pca_model.fit_transform(data_standardized)
247
+
248
+ # Create params dictionary
249
+ pca_params = {
250
+ 'pca_model': pca_model,
251
+ 'mean': mean,
252
+ 'std': std,
253
+ 'num_components': num_components,
254
+ 'feature_dim': data.shape[1],
255
+ 'explained_variance_ratio': pca_model.explained_variance_ratio_,
256
+ 'cumulative_variance': np.cumsum(pca_model.explained_variance_ratio_)
257
+ }
258
+
259
+ return pca_params, data_reduced
260
+
261
+
262
+ def apply_pca_transform(data, pca_params):
263
+ """
264
+ Apply saved PCA transformation to new data
265
+ CRITICAL: This uses the saved mean/std/PCA from training
266
+
267
+ Args:
268
+ data: New data to transform (n_samples, n_features)
269
+ pca_params: Dictionary from fit_pca_transformer
270
+
271
+ Returns:
272
+ Transformed data
273
+ """
274
+
275
+ # Standardize using training mean/std
276
+ data_standardized = (data - pca_params['mean']) / pca_params['std']
277
+
278
+ # Apply PCA transformation
279
+ # Projects new data onto the same principal components computed from training data
280
+ data_reduced = pca_params['pca_model'].transform(data_standardized)
281
+
282
+ return data_reduced
283
+
284
+
285
+ def train_svm_model(features, labels, test_size=0.2, kernel='rbf', C=1.0):
286
+ """
287
+ Train an SVM model and return both the model and performance metrics
288
+
289
+ Args:
290
+ features: Feature matrix (n_samples, n_features)
291
+ labels: Label array (n_samples,)
292
+ test_size: Proportion for test split
293
+ kernel: SVM kernel type
294
+ C: SVM regularization parameter
295
+
296
+ Returns:
297
+ Dictionary containing model and metrics
298
+ """
299
+
300
+ # Check if labels are one-hot encoded
301
+ if labels.ndim > 1 and labels.shape[1] > 1:
302
+ labels = np.argmax(labels, axis=1)
303
+
304
+ # Split data
305
+ X_train, X_test, y_train, y_test = train_test_split(
306
+ features, labels, test_size=test_size, random_state=42, stratify=labels
307
+ )
308
+
309
+ # Train SVM
310
+ svm_model = SVC(kernel=kernel, C=C, random_state=42)
311
+ svm_model.fit(X_train, y_train)
312
+
313
+ # Evaluate
314
+ y_train_pred = svm_model.predict(X_train)
315
+ y_test_pred = svm_model.predict(X_test)
316
+
317
+ train_accuracy = accuracy_score(y_train, y_train_pred)
318
+ test_accuracy = accuracy_score(y_test, y_test_pred)
319
+ test_f1 = f1_score(y_test, y_test_pred, average='macro')
320
+
321
+ print(f'Train Accuracy: {train_accuracy:.4f}')
322
+ print(f'Test Accuracy: {test_accuracy:.4f}')
323
+ print(f'Test F1-score: {test_f1:.4f}')
324
+
325
+ results = {
326
+ 'model': svm_model,
327
+ 'train_accuracy': train_accuracy,
328
+ 'test_accuracy': test_accuracy,
329
+ 'test_f1': test_f1
330
+ }
331
+
332
+ return results