-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupervised.py
More file actions
486 lines (402 loc) Β· 19.2 KB
/
supervised.py
File metadata and controls
486 lines (402 loc) Β· 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import os
import pandas as pd
import numpy as np
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
# Import all supervised learning models
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import MultinomialNB
# For ensemble methods
from sklearn.ensemble import VotingClassifier
from sklearn.metrics import precision_recall_fscore_support
# π Paths
folder_path = 'posts_all/'
labels_file = 'labels.csv'
# π₯ Load labels
df_labels = pd.read_csv(labels_file)
# π Read texts and labels
texts, labels = [], []
for _, row in df_labels.iterrows():
file_path = os.path.join(folder_path, row['filename'])
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
content = ''.join(lines[1:]).strip() # Skip label line
texts.append(content)
labels.append(row['label'])
print(f"π Loaded {len(texts)} documents")
print(f"π Label distribution: {Counter(labels)}")
# π Filter out labels with < 2 samples
label_counts = Counter(labels)
filtered_texts, filtered_labels = [], []
for text, label in zip(texts, labels):
if label_counts[label] >= 2:
filtered_texts.append(text)
filtered_labels.append(label)
print(f"π After filtering: {len(filtered_texts)} documents")
print(f"π Filtered label distribution: {Counter(filtered_labels)}")
# π Vectorize text using TF-IDF
vectorizer = TfidfVectorizer(
stop_words='english',
max_features=5000,
min_df=2,
max_df=0.8,
ngram_range=(1, 2)
)
X = vectorizer.fit_transform(filtered_texts)
y = filtered_labels
print(f"π TF-IDF matrix shape: {X.shape}")
print(f"π Number of unique labels: {len(set(y))}")
# π Train-test split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
print(f"π Training set size: {X_train.shape[0]}")
print(f"π Test set size: {X_test.shape[0]}")
# π€ DEFINE ALL MODELS
print("\n" + "="*60)
print("π€ TRAINING 5 SUPERVISED LEARNING MODELS")
print("="*60)
# Model 1: K-Nearest Neighbors
print("\n1οΈβ£ Training K-Nearest Neighbors...")
knn = KNeighborsClassifier(n_neighbors=5, weights='distance')
knn.fit(X_train, y_train)
knn_pred = knn.predict(X_test)
knn_accuracy = accuracy_score(y_test, knn_pred)
knn_cv_scores = cross_val_score(knn, X_train, y_train, cv=5)
print(f"β
KNN Accuracy: {knn_accuracy:.4f}")
# Model 2: Random Forest
print("\n2οΈβ£ Training Random Forest...")
rf = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)
rf.fit(X_train, y_train)
rf_pred = rf.predict(X_test)
rf_accuracy = accuracy_score(y_test, rf_pred)
rf_cv_scores = cross_val_score(rf, X_train, y_train, cv=5)
print(f"β
Random Forest Accuracy: {rf_accuracy:.4f}")
# Model 3: Support Vector Machine
print("\n3οΈβ£ Training Support Vector Machine...")
svm = SVC(kernel='rbf', random_state=42, probability=True)
svm.fit(X_train, y_train)
svm_pred = svm.predict(X_test)
svm_accuracy = accuracy_score(y_test, svm_pred)
svm_cv_scores = cross_val_score(svm, X_train, y_train, cv=5)
print(f"β
SVM Accuracy: {svm_accuracy:.4f}")
# Model 4: Logistic Regression
print("\n4οΈβ£ Training Logistic Regression...")
lr = LogisticRegression(random_state=42, max_iter=1000)
lr.fit(X_train, y_train)
lr_pred = lr.predict(X_test)
lr_accuracy = accuracy_score(y_test, lr_pred)
lr_cv_scores = cross_val_score(lr, X_train, y_train, cv=5)
print(f"β
Logistic Regression Accuracy: {lr_accuracy:.4f}")
# Model 5: Naive Bayes
print("\n5οΈβ£ Training Naive Bayes...")
nb = MultinomialNB(alpha=1.0)
nb.fit(X_train, y_train)
nb_pred = nb.predict(X_test)
nb_accuracy = accuracy_score(y_test, nb_pred)
nb_cv_scores = cross_val_score(nb, X_train, y_train, cv=5)
print(f"β
Naive Bayes Accuracy: {nb_accuracy:.4f}")
# π ENSEMBLE METHOD - VOTING CLASSIFIER
print("\n" + "="*60)
print("π CREATING ENSEMBLE MODEL")
print("="*60)
# Create ensemble with all models
ensemble = VotingClassifier(
estimators=[
('knn', knn),
('rf', rf),
('svm', svm),
('lr', lr),
('nb', nb)
],
voting='soft' # Use probability voting
)
ensemble.fit(X_train, y_train)
ensemble_pred = ensemble.predict(X_test)
ensemble_accuracy = accuracy_score(y_test, ensemble_pred)
ensemble_cv_scores = cross_val_score(ensemble, X_train, y_train, cv=5)
print(f"β
Ensemble Accuracy: {ensemble_accuracy:.4f}")
# π CALCULATE DETAILED METRICS FOR ALL MODELS
def calculate_metrics(y_true, y_pred, model_name):
accuracy = accuracy_score(y_true, y_pred)
precision, recall, f1, _ = precision_recall_fscore_support(y_true, y_pred, average='weighted')
return {
'Model': model_name,
'Accuracy': accuracy,
'Precision': precision,
'Recall': recall,
'F1-Score': f1
}
# Calculate metrics for all models
all_metrics = []
models_data = [
(knn_pred, 'K-Nearest Neighbors', knn_cv_scores),
(rf_pred, 'Random Forest', rf_cv_scores),
(svm_pred, 'Support Vector Machine', svm_cv_scores),
(lr_pred, 'Logistic Regression', lr_cv_scores),
(nb_pred, 'Naive Bayes', nb_cv_scores),
(ensemble_pred, 'Ensemble (Voting)', ensemble_cv_scores)
]
for pred, name, cv_scores in models_data:
metrics = calculate_metrics(y_test, pred, name)
metrics['CV_Mean'] = cv_scores.mean()
metrics['CV_Std'] = cv_scores.std()
all_metrics.append(metrics)
# π CREATE COMPREHENSIVE RESULTS TABLE
print("\n" + "="*80)
print("π COMPREHENSIVE RESULTS TABLE - TABLEAU FORMAT")
print("="*80)
results_df = pd.DataFrame(all_metrics)
results_df['Accuracy'] = results_df['Accuracy'].round(4)
results_df['Precision'] = results_df['Precision'].round(4)
results_df['Recall'] = results_df['Recall'].round(4)
results_df['F1-Score'] = results_df['F1-Score'].round(4)
results_df['CV_Mean'] = results_df['CV_Mean'].round(4)
results_df['CV_Std'] = results_df['CV_Std'].round(4)
# Create a more detailed tableau-style table
print("\nπ― MAIN PERFORMANCE METRICS TABLE")
print("β" + "β" * 28 + "β¬" + "β" * 12 + "β¬" + "β" * 12 + "β¬" + "β" * 10 + "β¬" + "β" * 10 + "β")
print("β{:<28}β{:>12}β{:>12}β{:>10}β{:>10}β".format("Model", "Accuracy", "Precision", "Recall", "F1-Score"))
print("β" + "β" * 28 + "βΌ" + "β" * 12 + "βΌ" + "β" * 12 + "βΌ" + "β" * 10 + "βΌ" + "β" * 10 + "β€")
for _, row in results_df.iterrows():
print("β{:<28}β{:>12.4f}β{:>12.4f}β{:>10.4f}β{:>10.4f}β".format(
row['Model'], row['Accuracy'], row['Precision'], row['Recall'], row['F1-Score']))
print("β" + "β" * 28 + "β΄" + "β" * 12 + "β΄" + "β" * 12 + "β΄" + "β" * 10 + "β΄" + "β" * 10 + "β")
print("\nπ CROSS-VALIDATION RESULTS TABLE")
print("β" + "β" * 28 + "β¬" + "β" * 15 + "β¬" + "β" * 15 + "β")
print("β{:<28}β{:>15}β{:>15}β".format("Model", "CV Mean", "CV Std Dev"))
print("β" + "β" * 28 + "βΌ" + "β" * 15 + "βΌ" + "β" * 15 + "β€")
for _, row in results_df.iterrows():
print("β{:<28}β{:>15.4f}β{:>15.4f}β".format(
row['Model'], row['CV_Mean'], row['CV_Std']))
print("β" + "β" * 28 + "β΄" + "β" * 15 + "β΄" + "β" * 15 + "β")
print("\nπ RANKING TABLE (By Accuracy)")
print("β" + "β" * 6 + "β¬" + "β" * 28 + "β¬" + "β" * 12 + "β¬" + "β" * 15 + "β")
print("β{:<6}β{:<28}β{:>12}β{:>15}β".format("Rank", "Model", "Accuracy", "Performance"))
print("β" + "β" * 6 + "βΌ" + "β" * 28 + "βΌ" + "β" * 12 + "βΌ" + "β" * 15 + "β€")
# Sort by accuracy for ranking
sorted_results = results_df.sort_values('Accuracy', ascending=False).reset_index(drop=True)
performance_levels = ['π₯ Excellent', 'π₯ Very Good', 'π₯ Good', 'π Fair', 'π Average', 'β‘ Baseline']
for i, (_, row) in enumerate(sorted_results.iterrows()):
perf = performance_levels[i] if i < len(performance_levels) else 'π Average'
print("β{:<6}β{:<28}β{:>12.4f}β{:>15}β".format(
i+1, row['Model'], row['Accuracy'], perf))
print("β" + "β" * 6 + "β΄" + "β" * 28 + "β΄" + "β" * 12 + "β΄" + "β" * 15 + "β")
# Additional summary statistics
print("\nπ SUMMARY STATISTICS")
print("β" + "β" * 20 + "β¬" + "β" * 15 + "β")
print("β{:<20}β{:>15}β".format("Statistic", "Value"))
print("β" + "β" * 20 + "βΌ" + "β" * 15 + "β€")
print("β{:<20}β{:>15.4f}β".format("Mean Accuracy", results_df['Accuracy'].mean()))
print("β{:<20}β{:>15.4f}β".format("Std Accuracy", results_df['Accuracy'].std()))
print("β{:<20}β{:>15.4f}β".format("Max Accuracy", results_df['Accuracy'].max()))
print("β{:<20}β{:>15.4f}β".format("Min Accuracy", results_df['Accuracy'].min()))
print("β{:<20}β{:>15.4f}β".format("Accuracy Range", results_df['Accuracy'].max() - results_df['Accuracy'].min()))
print("β" + "β" * 20 + "β΄" + "β" * 15 + "β")
print(results_df.to_string(index=False))
# π ACCURACY COMPARISON CHART
print("\n" + "="*60)
print("π CREATING VISUALIZATION")
print("="*60)
# Create accuracy comparison chart
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))
# Chart 1: Test Accuracy Comparison
models = results_df['Model']
accuracies = results_df['Accuracy']
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3']
bars1 = ax1.bar(models, accuracies, color=colors)
ax1.set_title('Test Accuracy Comparison', fontsize=14, fontweight='bold')
ax1.set_ylabel('Accuracy')
ax1.set_ylim(0, 1)
ax1.tick_params(axis='x', rotation=45)
# Add value labels on bars
for bar, acc in zip(bars1, accuracies):
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height + 0.01,
f'{acc:.3f}', ha='center', va='bottom', fontweight='bold')
# Chart 2: Cross-Validation Scores
cv_means = results_df['CV_Mean']
cv_stds = results_df['CV_Std']
bars2 = ax2.bar(models, cv_means, yerr=cv_stds, color=colors, alpha=0.7, capsize=5)
ax2.set_title('Cross-Validation Accuracy (5-Fold)', fontsize=14, fontweight='bold')
ax2.set_ylabel('CV Accuracy')
ax2.set_ylim(0, 1)
ax2.tick_params(axis='x', rotation=45)
# Add value labels on bars
for bar, mean, std in zip(bars2, cv_means, cv_stds):
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height + std + 0.01,
f'{mean:.3f}Β±{std:.3f}', ha='center', va='bottom', fontweight='bold')
plt.tight_layout()
plt.show()
# π DETAILED METRICS HEATMAP
fig, ax = plt.subplots(figsize=(10, 6))
metrics_for_heatmap = results_df[['Model', 'Accuracy', 'Precision', 'Recall', 'F1-Score']].set_index('Model')
sns.heatmap(metrics_for_heatmap, annot=True, cmap='YlOrRd', fmt='.3f', ax=ax)
ax.set_title('Model Performance Metrics Heatmap', fontsize=14, fontweight='bold')
plt.tight_layout()
plt.show()
# π IDENTIFY BEST MODEL
best_model_idx = results_df['Accuracy'].idxmax()
best_model = results_df.loc[best_model_idx]
print("\n" + "="*60)
print("π BEST MODEL SUMMARY")
print("="*60)
print(f"π₯ Best Model: {best_model['Model']}")
print(f"π Test Accuracy: {best_model['Accuracy']:.4f}")
print(f"π Cross-Validation: {best_model['CV_Mean']:.4f} Β± {best_model['CV_Std']:.4f}")
print(f"π Precision: {best_model['Precision']:.4f}")
print(f"π Recall: {best_model['Recall']:.4f}")
print(f"π F1-Score: {best_model['F1-Score']:.4f}")
# π DETAILED CLASSIFICATION REPORT FOR BEST MODEL
print(f"\nπ Detailed Classification Report for {best_model['Model']}:")
print("-" * 60)
# Get predictions from best model
if best_model['Model'] == 'K-Nearest Neighbors':
best_pred = knn_pred
elif best_model['Model'] == 'Random Forest':
best_pred = rf_pred
elif best_model['Model'] == 'Support Vector Machine':
best_pred = svm_pred
elif best_model['Model'] == 'Logistic Regression':
best_pred = lr_pred
elif best_model['Model'] == 'Naive Bayes':
best_pred = nb_pred
else:
best_pred = ensemble_pred
print(classification_report(y_test, best_pred))
# π CONFUSION MATRIX FOR BEST MODEL
fig, ax = plt.subplots(figsize=(8, 6))
cm = confusion_matrix(y_test, best_pred)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', ax=ax)
ax.set_title(f'Confusion Matrix - {best_model["Model"]}', fontsize=14, fontweight='bold')
ax.set_xlabel('Predicted')
ax.set_ylabel('Actual')
plt.tight_layout()
plt.show()
# πΎ SAVE RESULTS
results_df.to_csv('model_comparison_results.csv', index=False)
print(f"\nπΎ Results saved to 'model_comparison_results.csv'")
print("\nβ
Analysis Complete!")
print(f"π― Best performing model: {best_model['Model']} with {best_model['Accuracy']:.4f} accuracy")
# π SAVE RESULTS TO MARKDOWN FILE
# π SAVE REPORT TO MARKDOWN FILE
report_lines = []
report_lines.append("# π Supervised Model Comparison Report\n")
report_lines.append(f"**Total documents used:** {len(filtered_texts)}\n")
report_lines.append(f"**TF-IDF Features:** {X.shape[1]}\n")
report_lines.append(f"**Number of unique labels:** {len(set(y))}\n\n")
# π Add metrics table
report_lines.append("## π Model Performance Metrics\n")
report_lines.append(results_df.to_markdown(index=False))
report_lines.append("\n")
# π Ranking Table
report_lines.append("## π Model Ranking (by Accuracy)\n")
for i, (_, row) in enumerate(sorted_results.iterrows()):
perf = performance_levels[i] if i < len(performance_levels) else 'π Average'
report_lines.append(f"{i+1}. **{row['Model']}** β Accuracy: **{row['Accuracy']:.4f}** ({perf})")
report_lines.append("\n")
# π Summary Statistics
report_lines.append("## π Summary Statistics\n")
report_lines.append(f"- **Mean Accuracy:** {results_df['Accuracy'].mean():.4f}")
report_lines.append(f"- **Std Accuracy:** {results_df['Accuracy'].std():.4f}")
report_lines.append(f"- **Max Accuracy:** {results_df['Accuracy'].max():.4f}")
report_lines.append(f"- **Min Accuracy:** {results_df['Accuracy'].min():.4f}")
report_lines.append(f"- **Accuracy Range:** {(results_df['Accuracy'].max() - results_df['Accuracy'].min()):.4f}\n")
# π Best Model Summary
report_lines.append("## π₯ Best Model Summary\n")
report_lines.append(f"- **Best Model:** {best_model['Model']}")
report_lines.append(f"- **Test Accuracy:** {best_model['Accuracy']:.4f}")
report_lines.append(f"- **CV Mean Accuracy:** {best_model['CV_Mean']:.4f}")
report_lines.append(f"- **Precision:** {best_model['Precision']:.4f}")
report_lines.append(f"- **Recall:** {best_model['Recall']:.4f}")
report_lines.append(f"- **F1-Score:** {best_model['F1-Score']:.4f}\n")
# π Classification Report for Best Model
report_lines.append(f"## π Detailed Classification Report: {best_model['Model']}\n")
report_lines.append("```\n")
report_lines.append(classification_report(y_test, best_pred))
report_lines.append("```\n")
# π SAVE REPORT TO MARKDOWN FILE
report_lines = []
report_lines.append("# π Supervised Model Comparison Report\n")
report_lines.append(f"**Total documents used:** {len(filtered_texts)}\n")
report_lines.append(f"**TF-IDF Features:** {X.shape[1]}\n")
report_lines.append(f"**Number of unique labels:** {len(set(y))}\n\n")
# π Add metrics table
report_lines.append("## π Model Performance Metrics\n")
report_lines.append(results_df.to_markdown(index=False))
report_lines.append("\n")
# π Ranking Table
report_lines.append("## π Model Ranking (by Accuracy)\n")
for i, (_, row) in enumerate(sorted_results.iterrows()):
perf = performance_levels[i] if i < len(performance_levels) else 'π Average'
report_lines.append(f"{i+1}. **{row['Model']}** β Accuracy: **{row['Accuracy']:.4f}** ({perf})")
report_lines.append("\n")
# π Summary Statistics
report_lines.append("## π Summary Statistics\n")
report_lines.append(f"- **Mean Accuracy:** {results_df['Accuracy'].mean():.4f}")
report_lines.append(f"- **Std Accuracy:** {results_df['Accuracy'].std():.4f}")
report_lines.append(f"- **Max Accuracy:** {results_df['Accuracy'].max():.4f}")
report_lines.append(f"- **Min Accuracy:** {results_df['Accuracy'].min():.4f}")
report_lines.append(f"- **Accuracy Range:** {(results_df['Accuracy'].max() - results_df['Accuracy'].min()):.4f}\n")
# π Best Model Summary
report_lines.append("## π₯ Best Model Summary\n")
report_lines.append(f"- **Best Model:** {best_model['Model']}")
report_lines.append(f"- **Test Accuracy:** {best_model['Accuracy']:.4f}")
report_lines.append(f"- **CV Mean Accuracy:** {best_model['CV_Mean']:.4f}")
report_lines.append(f"- **Precision:** {best_model['Precision']:.4f}")
report_lines.append(f"- **Recall:** {best_model['Recall']:.4f}")
report_lines.append(f"- **F1-Score:** {best_model['F1-Score']:.4f}\n")
# π Classification Report for Best Model
report_lines.append(f"## π Detailed Classification Report: {best_model['Model']}\n")
report_lines.append("```\n")
report_lines.append(classification_report(y_test, best_pred))
report_lines.append("```\n")
# π SAVE REPORT TO MARKDOWN FILE
report_lines = []
report_lines.append("# π Supervised Model Comparison Report\n")
report_lines.append(f"**Total documents used:** {len(filtered_texts)}\n")
report_lines.append(f"**TF-IDF Features:** {X.shape[1]}\n")
report_lines.append(f"**Number of unique labels:** {len(set(y))}\n\n")
# π Add metrics table
report_lines.append("## π Model Performance Metrics\n")
report_lines.append(results_df.to_markdown(index=False))
report_lines.append("\n")
# π Ranking Table
report_lines.append("## π Model Ranking (by Accuracy)\n")
for i, (_, row) in enumerate(sorted_results.iterrows()):
perf = performance_levels[i] if i < len(performance_levels) else 'π Average'
report_lines.append(f"{i+1}. **{row['Model']}** β Accuracy: **{row['Accuracy']:.4f}** ({perf})")
report_lines.append("\n")
# π Summary Statistics
report_lines.append("## π Summary Statistics\n")
report_lines.append(f"- **Mean Accuracy:** {results_df['Accuracy'].mean():.4f}")
report_lines.append(f"- **Std Accuracy:** {results_df['Accuracy'].std():.4f}")
report_lines.append(f"- **Max Accuracy:** {results_df['Accuracy'].max():.4f}")
report_lines.append(f"- **Min Accuracy:** {results_df['Accuracy'].min():.4f}")
report_lines.append(f"- **Accuracy Range:** {(results_df['Accuracy'].max() - results_df['Accuracy'].min()):.4f}\n")
# π Best Model Summary
report_lines.append("## π₯ Best Model Summary\n")
report_lines.append(f"- **Best Model:** {best_model['Model']}")
report_lines.append(f"- **Test Accuracy:** {best_model['Accuracy']:.4f}")
report_lines.append(f"- **CV Mean Accuracy:** {best_model['CV_Mean']:.4f}")
report_lines.append(f"- **Precision:** {best_model['Precision']:.4f}")
report_lines.append(f"- **Recall:** {best_model['Recall']:.4f}")
report_lines.append(f"- **F1-Score:** {best_model['F1-Score']:.4f}\n")
# π Classification Report for Best Model
report_lines.append(f"## π Detailed Classification Report: {best_model['Model']}\n")
report_lines.append("```\n")
report_lines.append(classification_report(y_test, best_pred))
report_lines.append("```\n")
# Save to markdown file
with open("supervised_model_comparison.md", "w") as f:
f.writelines([line + "\n" for line in report_lines])
print("\nβ
Markdown report saved to 'supervised_model_comparison.md'")