annaferrari02 commited on
Commit
f1914db
·
verified ·
1 Parent(s): a63e75d

upload files

Browse files
multiclass_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb36865a9d123033efa475cc7ee9bb019fc1fea128f461fd41e6a62e48b2c72d
3
+ size 474442
pca_params.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc3a46612a41dbe514a415b97c34af0bcffdc06d91f2c47b0504814c7126d509
3
+ size 7409478
script.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script for Hugging Face competition submission
3
+ Fixed 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,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training script for surgical instrument classification
3
+ Generates files needed for Hugging Face submission
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, fit_pca_transformer, train_svm_model
12
+
13
+
14
+ def train_and_save_model(base_path, images_folder, gt_csv, save_dir, n_components=100):
15
+ """
16
+ Complete training pipeline that saves everything needed for submission
17
+
18
+ Args:
19
+ base_path: Base directory path
20
+ images_folder: Folder name containing images
21
+ gt_csv: Ground truth CSV filename
22
+ save_dir: Directory to save model artifacts
23
+ n_components: Number of PCA components
24
+ """
25
+
26
+ print("="*80)
27
+ print("TRAINING SURGICAL INSTRUMENT CLASSIFIER")
28
+ print("="*80)
29
+
30
+ # Setup paths
31
+ PATH_TO_GT = os.path.join(base_path, gt_csv)
32
+ PATH_TO_IMAGES = os.path.join(base_path, images_folder)
33
+
34
+ print(f"\nConfiguration:")
35
+ print(f" Ground Truth: {PATH_TO_GT}")
36
+ print(f" Images: {PATH_TO_IMAGES}")
37
+ print(f" PCA Components: {n_components}")
38
+ print(f" Save directory: {save_dir}")
39
+
40
+ # Load ground truth
41
+ df = pd.read_csv(PATH_TO_GT)
42
+ print(f"\nLoaded {len(df)} training samples")
43
+ print(f"\nLabel distribution:")
44
+ print(df['category_id'].value_counts().sort_index())
45
+
46
+ # Extract features
47
+ print(f"\n{'='*80}")
48
+ print("STEP 1: FEATURE EXTRACTION")
49
+ print("="*80)
50
+
51
+ features = []
52
+ labels = []
53
+
54
+ for i in range(len(df)):
55
+ if i % 500 == 0:
56
+ print(f" Processing {i}/{len(df)}...")
57
+
58
+ image_name = df.iloc[i]["file_name"]
59
+ label = df.iloc[i]["category_id"]
60
+
61
+ path_to_image = os.path.join(PATH_TO_IMAGES, image_name)
62
+
63
+ try:
64
+ image = cv2.imread(path_to_image)
65
+ if image is None:
66
+ print(f" Warning: Could not read {image_name}, skipping...")
67
+ continue
68
+
69
+ # Extract features with enhanced configuration
70
+ image_features = extract_features_from_image(image)
71
+
72
+ features.append(image_features)
73
+ labels.append(label)
74
+
75
+ except Exception as e:
76
+ print(f" Error processing {image_name}: {e}")
77
+ continue
78
+
79
+ features_array = np.array(features)
80
+ labels_array = np.array(labels)
81
+
82
+ print(f"\nFeature extraction complete!")
83
+ print(f" Features shape: {features_array.shape}")
84
+ print(f" Labels shape: {labels_array.shape}")
85
+ print(f" Feature dimension: {features_array.shape[1]}")
86
+
87
+ # Apply PCA
88
+ print(f"\n{'='*80}")
89
+ print("STEP 2: DIMENSIONALITY REDUCTION (PCA)")
90
+ print("="*80)
91
+
92
+ pca_params, features_reduced = fit_pca_transformer(features_array, n_components)
93
+
94
+ print(f" Reduced from {features_array.shape[1]} to {n_components} dimensions")
95
+ print(f" Explained variance: {pca_params['cumulative_variance'][-1]:.4f}")
96
+
97
+ # Train SVM
98
+ print(f"\n{'='*80}")
99
+ print("STEP 3: TRAINING SVM CLASSIFIER")
100
+ print("="*80)
101
+
102
+ train_results = train_svm_model(features_reduced, labels_array)
103
+
104
+ svm_model = train_results['model']
105
+
106
+ print(f"\nTraining complete!")
107
+ print(f" Support vectors: {len(svm_model.support_)}")
108
+
109
+ # Save model artifacts
110
+ print(f"\n{'='*80}")
111
+ print("STEP 4: SAVING MODEL ARTIFACTS")
112
+ print("="*80)
113
+
114
+ os.makedirs(save_dir, exist_ok=True)
115
+
116
+ # Save SVM model
117
+ model_path = os.path.join(save_dir, "multiclass_model.pkl")
118
+ with open(model_path, "wb") as f:
119
+ pickle.dump(svm_model, f)
120
+ print(f" ✓ Saved SVM model: {model_path}")
121
+
122
+ # Save PCA parameters
123
+ pca_path = os.path.join(save_dir, "pca_params.pkl")
124
+ with open(pca_path, "wb") as f:
125
+ pickle.dump(pca_params, f)
126
+ print(f" ✓ Saved PCA params: {pca_path}")
127
+
128
+ print(f"\n{'='*80}")
129
+ print("TRAINING COMPLETE!")
130
+ print("="*80)
131
+ print(f"\nFinal Results:")
132
+ print(f" Train Accuracy: {train_results['train_accuracy']:.4f}")
133
+ print(f" Test Accuracy: {train_results['test_accuracy']:.4f}")
134
+ print(f" Test F1-score: {train_results['test_f1']:.4f}")
135
+ print(f"\nFiles saved to: {save_dir}")
136
+ print(f"\nNext steps:")
137
+ print(f" 1. Create a 'utils' folder in your HuggingFace repository")
138
+ print(f" 2. Copy utils.py into the 'utils' folder")
139
+ print(f" 3. Copy script.py, multiclass_model.pkl, and pca_params.pkl to the repository root")
140
+ print(f" 4. Create an empty __init__.py file in the 'utils' folder")
141
+ print(f" 5. Submit to competition!")
142
+
143
+
144
+ if __name__ == "__main__":
145
+
146
+ # CONFIGURATION - Adjust these paths to your setup
147
+ BASE_PATH = "C:/Users/anna2/ISM/ANNA/phase1a2"
148
+ IMAGES_FOLDER = "C:/Users/anna2/ISM/Images"
149
+ GT_CSV = "C:/Users/anna2/ISM/Baselines/phase_1a/gt_for_classification_multiclass_from_filenames_0_index.csv"
150
+
151
+ SAVE_DIR = "C:/Users/anna2/ISM/ANNA/phase1a2/submission"
152
+
153
+ # Number of PCA components
154
+ N_COMPONENTS = 100
155
+
156
+ # Train and save
157
+ train_and_save_model(BASE_PATH, IMAGES_FOLDER, GT_CSV, SAVE_DIR, N_COMPONENTS)
utils/__pycache__/utils.cpython-312.pyc ADDED
Binary file (9.03 kB). View file
 
utils/utils.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for surgical instrument classification
3
+ Simplified version that maintains enhanced features
4
+ """
5
+
6
+ import cv2
7
+ import numpy as np
8
+ from skimage.feature.texture import graycomatrix, graycoprops
9
+ from skimage.feature import local_binary_pattern, hog
10
+ from sklearn.decomposition import PCA
11
+ from sklearn.svm import SVC
12
+ from sklearn.model_selection import train_test_split
13
+ from sklearn.metrics import accuracy_score, f1_score
14
+
15
+
16
+ def rgb_histogram(image, bins=256):
17
+ """Extract RGB histogram features"""
18
+ hist_features = []
19
+ for i in range(3): # RGB Channels
20
+ hist, _ = np.histogram(image[:, :, i], bins=bins, range=(0, 256), density=True)
21
+ hist_features.append(hist)
22
+ return np.concatenate(hist_features)
23
+
24
+
25
+ def hu_moments(image):
26
+ """Extract Hu moment features"""
27
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
28
+ moments = cv2.moments(gray)
29
+ hu_moments = cv2.HuMoments(moments).flatten()
30
+ return hu_moments
31
+
32
+
33
+ def glcm_features(image, distances=[1], angles=[0], levels=256, symmetric=True, normed=True):
34
+ """Extract GLCM texture features"""
35
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
36
+ glcm = graycomatrix(gray, distances=distances, angles=angles, levels=levels,
37
+ symmetric=symmetric, normed=normed)
38
+ contrast = graycoprops(glcm, 'contrast').flatten()
39
+ dissimilarity = graycoprops(glcm, 'dissimilarity').flatten()
40
+ homogeneity = graycoprops(glcm, 'homogeneity').flatten()
41
+ energy = graycoprops(glcm, 'energy').flatten()
42
+ correlation = graycoprops(glcm, 'correlation').flatten()
43
+ asm = graycoprops(glcm, 'ASM').flatten()
44
+ return np.concatenate([contrast, dissimilarity, homogeneity, energy, correlation, asm])
45
+
46
+
47
+ def local_binary_pattern_features(image, P=8, R=1):
48
+ """Extract Local Binary Pattern features"""
49
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
50
+ lbp = local_binary_pattern(gray, P, R, method='uniform')
51
+ (hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, P + 3),
52
+ range=(0, P + 2), density=True)
53
+ return hist
54
+
55
+
56
+ def hog_features(image, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2)):
57
+ """
58
+ Extract HOG (Histogram of Oriented Gradients) features
59
+ Great for capturing shape and edge information in surgical instruments
60
+ """
61
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
62
+
63
+ # Resize to standard size for consistency
64
+ gray_resized = cv2.resize(gray, (128, 128))
65
+
66
+ hog_features_vector = hog(
67
+ gray_resized,
68
+ orientations=orientations,
69
+ pixels_per_cell=pixels_per_cell,
70
+ cells_per_block=cells_per_block,
71
+ block_norm='L2-Hys',
72
+ feature_vector=True
73
+ )
74
+
75
+ return hog_features_vector
76
+
77
+
78
+ def luv_histogram(image, bins=32):
79
+ """
80
+ Extract histogram in LUV color space
81
+ LUV is perceptually uniform and better for underwater/surgical imaging
82
+ """
83
+ luv = cv2.cvtColor(image, cv2.COLOR_BGR2LUV)
84
+ hist_features = []
85
+ for i in range(3):
86
+ hist, _ = np.histogram(luv[:, :, i], bins=bins, range=(0, 256), density=True)
87
+ hist_features.append(hist)
88
+ return np.concatenate(hist_features)
89
+
90
+
91
+ def extract_features_from_image(image):
92
+ """
93
+ Extract enhanced features from image
94
+ Uses baseline features + HOG + LUV histogram for better performance
95
+
96
+ Args:
97
+ image: Input image (BGR format from cv2.imread)
98
+
99
+ Returns:
100
+ Feature vector as numpy array
101
+ """
102
+
103
+ # Baseline features
104
+ hist_features = rgb_histogram(image)
105
+ hu_features = hu_moments(image)
106
+ glcm_features_vector = glcm_features(image)
107
+ lbp_features = local_binary_pattern_features(image)
108
+
109
+ # Enhanced features
110
+ hog_feat = hog_features(image)
111
+ luv_hist = luv_histogram(image)
112
+
113
+ # Concatenate all features
114
+ image_features = np.concatenate([
115
+ hist_features,
116
+ hu_features,
117
+ glcm_features_vector,
118
+ lbp_features,
119
+ hog_feat,
120
+ luv_hist
121
+ ])
122
+
123
+ return image_features
124
+
125
+
126
+ def fit_pca_transformer(data, num_components):
127
+ """
128
+ Fit a PCA transformer on training data
129
+
130
+ Args:
131
+ data: Training data (n_samples, n_features)
132
+ num_components: Number of PCA components to keep
133
+
134
+ Returns:
135
+ pca_params: Dictionary containing PCA parameters
136
+ data_reduced: PCA-transformed data
137
+ """
138
+
139
+ # Standardize the data
140
+ mean = np.mean(data, axis=0)
141
+ std = np.std(data, axis=0)
142
+
143
+ # Avoid division by zero
144
+ std[std == 0] = 1.0
145
+
146
+ data_standardized = (data - mean) / std
147
+
148
+ # Fit PCA using sklearn
149
+ pca_model = PCA(n_components=num_components)
150
+ data_reduced = pca_model.fit_transform(data_standardized)
151
+
152
+ # Create params dictionary
153
+ pca_params = {
154
+ 'pca_model': pca_model,
155
+ 'mean': mean,
156
+ 'std': std,
157
+ 'num_components': num_components,
158
+ 'feature_dim': data.shape[1],
159
+ 'explained_variance_ratio': pca_model.explained_variance_ratio_,
160
+ 'cumulative_variance': np.cumsum(pca_model.explained_variance_ratio_)
161
+ }
162
+
163
+ return pca_params, data_reduced
164
+
165
+
166
+ def apply_pca_transform(data, pca_params):
167
+ """
168
+ Apply saved PCA transformation to new data
169
+ CRITICAL: This uses the saved mean/std/PCA from training
170
+
171
+ Args:
172
+ data: New data to transform (n_samples, n_features)
173
+ pca_params: Dictionary from fit_pca_transformer
174
+
175
+ Returns:
176
+ Transformed data
177
+ """
178
+
179
+ # Standardize using training mean/std
180
+ data_standardized = (data - pca_params['mean']) / pca_params['std']
181
+
182
+ # Apply PCA transformation
183
+ data_reduced = pca_params['pca_model'].transform(data_standardized)
184
+
185
+ return data_reduced
186
+
187
+
188
+ def train_svm_model(features, labels, test_size=0.2, kernel='rbf', C=1.0):
189
+ """
190
+ Train an SVM model and return both the model and performance metrics
191
+
192
+ Args:
193
+ features: Feature matrix (n_samples, n_features)
194
+ labels: Label array (n_samples,)
195
+ test_size: Proportion for test split
196
+ kernel: SVM kernel type
197
+ C: SVM regularization parameter
198
+
199
+ Returns:
200
+ Dictionary containing model and metrics
201
+ """
202
+
203
+ # Check if labels are one-hot encoded
204
+ if labels.ndim > 1 and labels.shape[1] > 1:
205
+ labels = np.argmax(labels, axis=1)
206
+
207
+ # Split data
208
+ X_train, X_test, y_train, y_test = train_test_split(
209
+ features, labels, test_size=test_size, random_state=42, stratify=labels
210
+ )
211
+
212
+ # Train SVM
213
+ svm_model = SVC(kernel=kernel, C=C, random_state=42)
214
+ svm_model.fit(X_train, y_train)
215
+
216
+ # Evaluate
217
+ y_train_pred = svm_model.predict(X_train)
218
+ y_test_pred = svm_model.predict(X_test)
219
+
220
+ train_accuracy = accuracy_score(y_train, y_train_pred)
221
+ test_accuracy = accuracy_score(y_test, y_test_pred)
222
+ test_f1 = f1_score(y_test, y_test_pred, average='macro')
223
+
224
+ print(f'Train Accuracy: {train_accuracy:.4f}')
225
+ print(f'Test Accuracy: {test_accuracy:.4f}')
226
+ print(f'Test F1-score: {test_f1:.4f}')
227
+
228
+ results = {
229
+ 'model': svm_model,
230
+ 'train_accuracy': train_accuracy,
231
+ 'test_accuracy': test_accuracy,
232
+ 'test_f1': test_f1
233
+ }
234
+
235
+ return results