-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
198 lines (152 loc) · 7.33 KB
/
Copy pathutils.py
File metadata and controls
198 lines (152 loc) · 7.33 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
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from typing import Dict, List, Tuple, Any
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
confusion_matrix, classification_report
)
import joblib
def compute_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> Dict[str, float]:
return {
'accuracy': accuracy_score(y_true, y_pred),
'precision': precision_score(y_true, y_pred),
'recall': recall_score(y_true, y_pred),
'f1': f1_score(y_true, y_pred)
}
def get_classification_report(y_true: np.ndarray, y_pred: np.ndarray,
target_names: List[str] = None) -> str:
if target_names is None:
target_names = ['Healthy', 'Parkinson']
return classification_report(y_true, y_pred, target_names=target_names)
def plot_confusion_matrix(y_true: np.ndarray, y_pred: np.ndarray,
model_name: str, save_path: str,
target_names: List[str] = None) -> None:
if target_names is None:
target_names = ['Healthy', 'Parkinson']
cm = confusion_matrix(y_true, y_pred)
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=target_names, yticklabels=target_names,
annot_kws={'size': 12})
plt.title(f'Confusion Matrix - {model_name}', fontsize=14, fontweight='bold')
plt.xlabel('Predicted Label', fontsize=12)
plt.ylabel('True Label', fontsize=12)
plt.tight_layout()
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.close()
print(f" ✓ Confusion matrix saved: {save_path}")
def plot_accuracy_comparison(results: Dict[str, Dict[str, float]],
save_path: str, pca_suffix: str = "") -> None:
model_names = list(results.keys())
accuracies = [results[model]['accuracy'] for model in model_names]
display_names = [name.replace('_no_pca', '').replace('_pca', '')
for name in model_names]
plt.figure(figsize=(10, 6))
bars = plt.bar(display_names, accuracies, color=['#3498db', '#2ecc71', '#e74c3c'])
for bar, acc in zip(bars, accuracies):
plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01,
f'{acc:.4f}', ha='center', va='bottom', fontsize=11, fontweight='bold')
plt.title(f'Model Accuracy Comparison {pca_suffix}'.strip(), fontsize=14, fontweight='bold')
plt.xlabel('Model', fontsize=12)
plt.ylabel('Accuracy', fontsize=12)
plt.ylim(0, 1.1)
plt.xticks(fontsize=10)
plt.tight_layout()
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.close()
print(f" ✓ Accuracy comparison saved: {save_path}")
def plot_pca_variance(pca, save_path: str) -> None:
explained_variance = pca.explained_variance_ratio_
cumulative_variance = np.cumsum(explained_variance)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
ax1.bar(range(1, len(explained_variance) + 1), explained_variance,
alpha=0.7, color='#3498db', edgecolor='black')
ax1.set_xlabel('Principal Component', fontsize=12)
ax1.set_ylabel('Explained Variance Ratio', fontsize=12)
ax1.set_title('Individual Explained Variance', fontsize=13, fontweight='bold')
ax1.grid(axis='y', alpha=0.3)
ax2.plot(range(1, len(cumulative_variance) + 1), cumulative_variance,
marker='o', markersize=8, linewidth=2, color='#e74c3c')
ax2.axhline(y=0.95, color='green', linestyle='--', linewidth=2,
label='95% Variance Threshold')
ax2.axhline(y=0.90, color='orange', linestyle='--', linewidth=2,
label='90% Variance Threshold')
ax2.set_xlabel('Number of Principal Components', fontsize=12)
ax2.set_ylabel('Cumulative Explained Variance', fontsize=12)
ax2.set_title('Cumulative Explained Variance', fontsize=13, fontweight='bold')
ax2.legend(fontsize=10)
ax2.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.close()
print(f" ✓ PCA variance plot saved: {save_path}")
n_components_90 = np.argmax(cumulative_variance >= 0.90) + 1
n_components_95 = np.argmax(cumulative_variance >= 0.95) + 1
print(f"\n📊 PCA Variance Summary:")
print(f" • Components for 90% variance: {n_components_90}")
print(f" • Components for 95% variance: {n_components_95}")
print(f" • Total variance retained: {cumulative_variance[-1]:.4f}")
def plot_feature_importance(feature_names: List[str], importances: np.ndarray,
model_name: str, save_path: str,
top_n: int = 15) -> None:
indices = np.argsort(importances)[::-1][:top_n]
top_features = [feature_names[i] for i in indices]
top_importances = importances[indices]
plt.figure(figsize=(12, 8))
colors = plt.cm.viridis(np.linspace(0.2, 0.8, len(top_features)))
bars = plt.barh(range(len(top_features)), top_importances, color=colors)
plt.yticks(range(len(top_features)), top_features, fontsize=9)
plt.xlabel('Importance', fontsize=12)
plt.title(f'Top {top_n} Feature Importances - {model_name}',
fontsize=14, fontweight='bold')
plt.gca().invert_yaxis()
plt.tight_layout()
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.close()
print(f" ✓ Feature importance plot saved: {save_path}")
def save_model(model: Any, filepath: str) -> None:
os.makedirs(os.path.dirname(filepath), exist_ok=True)
joblib.dump(model, filepath)
print(f" ✓ Model saved: {filepath}")
def load_model(filepath: str) -> Any:
if not os.path.exists(filepath):
raise FileNotFoundError(f"Model file not found: {filepath}")
return joblib.load(filepath)
def save_scaler(scaler: Any, filepath: str) -> None:
os.makedirs(os.path.dirname(filepath), exist_ok=True)
joblib.dump(scaler, filepath)
print(f" ✓ Scaler saved: {filepath}")
def save_pca(pca: Any, filepath: str) -> None:
os.makedirs(os.path.dirname(filepath), exist_ok=True)
joblib.dump(pca, filepath)
print(f" ✓ PCA saved: {filepath}")
def save_results_to_csv(results: List[Dict[str, Any]], filepath: str) -> None:
df = pd.DataFrame(results)
column_order = ['model_name', 'pca', 'accuracy', 'precision', 'recall', 'f1']
existing_columns = [col for col in column_order if col in df.columns]
df = df[existing_columns]
df.to_csv(filepath, index=False)
print(f"\n📊 Results saved to: {filepath}")
print(df.to_string(index=False))
def save_best_model(model_name: str, filepath: str) -> None:
with open(filepath, 'w') as f:
f.write(model_name)
print(f"\n🏆 Best model saved: {filepath}")
print(f" Best Model: {model_name}")
def get_best_model(results: List[Dict[str, Any]], metric: str = 'accuracy') -> Tuple[str, float]:
best = max(results, key=lambda x: x[metric])
return best['model_name'], best[metric]
def ensure_directory(filepath: str) -> None:
directory = os.path.dirname(filepath)
if directory:
os.makedirs(directory, exist_ok=True)
def get_wav_files(directory: str) -> List[str]:
wav_files = []
for root, _, files in os.walk(directory):
for file in files:
if file.lower().endswith('.wav'):
wav_files.append(os.path.join(root, file))
return sorted(wav_files)