-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_multiclass.py
More file actions
232 lines (194 loc) · 7.17 KB
/
test_multiclass.py
File metadata and controls
232 lines (194 loc) · 7.17 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
#!/usr/bin/env python3
"""
Test multiclass classification: TurboCat vs CatBoost vs LightGBM vs XGBoost
"""
import numpy as np
import time
import warnings
from sklearn.datasets import load_iris, load_wine, load_digits, make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, f1_score
from sklearn.preprocessing import StandardScaler
warnings.filterwarnings('ignore')
# Import models
import sys
sys.path.insert(0, 'build')
from _turbocat import TurboCatClassifier
try:
from catboost import CatBoostClassifier
HAS_CATBOOST = True
except ImportError:
HAS_CATBOOST = False
try:
import lightgbm as lgb
HAS_LIGHTGBM = True
except ImportError:
HAS_LIGHTGBM = False
try:
import xgboost as xgb
HAS_XGBOOST = True
except ImportError:
HAS_XGBOOST = False
# Common hyperparameters
COMMON_PARAMS = {
'n_estimators': 100,
'learning_rate': 0.1,
'max_depth': 6,
}
def evaluate_model(name, model, X_train, X_test, y_train, y_test):
"""Train and evaluate a model"""
try:
# Training time
start = time.perf_counter()
model.fit(X_train, y_train)
train_time = time.perf_counter() - start
# Inference time
start = time.perf_counter()
y_pred = model.predict(X_test)
if hasattr(y_pred, 'flatten'):
y_pred = y_pred.flatten()
inference_time = time.perf_counter() - start
# Metrics
acc = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred, average='weighted')
return {
'accuracy': acc,
'f1': f1,
'train_time': train_time,
'inference_time': inference_time,
}
except Exception as e:
print(f" {name} error: {e}")
return None
def run_benchmark(name, X, y):
"""Run benchmark on a dataset"""
print(f"\n{'='*70}")
print(f"Dataset: {name}")
print(f"Samples: {X.shape[0]}, Features: {X.shape[1]}, Classes: {len(np.unique(y))}")
print('='*70)
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Scale features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train).astype(np.float32)
X_test = scaler.transform(X_test).astype(np.float32)
y_train = y_train.astype(np.float32)
y_test = y_test.astype(np.int32)
results = {}
# TurboCat
print("\n Training TurboCat...")
tc_model = TurboCatClassifier(
n_estimators=COMMON_PARAMS['n_estimators'],
learning_rate=COMMON_PARAMS['learning_rate'],
max_depth=COMMON_PARAMS['max_depth'],
verbosity=0,
use_goss=True
)
results['TurboCat'] = evaluate_model('TurboCat', tc_model, X_train, X_test, y_train, y_test)
# CatBoost
if HAS_CATBOOST:
print(" Training CatBoost...")
cb_model = CatBoostClassifier(
iterations=COMMON_PARAMS['n_estimators'],
learning_rate=COMMON_PARAMS['learning_rate'],
depth=COMMON_PARAMS['max_depth'],
verbose=False,
allow_writing_files=False
)
results['CatBoost'] = evaluate_model('CatBoost', cb_model, X_train, X_test, y_train, y_test)
# LightGBM
if HAS_LIGHTGBM:
print(" Training LightGBM...")
lgb_model = lgb.LGBMClassifier(
n_estimators=COMMON_PARAMS['n_estimators'],
learning_rate=COMMON_PARAMS['learning_rate'],
max_depth=COMMON_PARAMS['max_depth'],
verbose=-1
)
results['LightGBM'] = evaluate_model('LightGBM', lgb_model, X_train, X_test, y_train, y_test)
# XGBoost
if HAS_XGBOOST:
print(" Training XGBoost...")
xgb_model = xgb.XGBClassifier(
n_estimators=COMMON_PARAMS['n_estimators'],
learning_rate=COMMON_PARAMS['learning_rate'],
max_depth=COMMON_PARAMS['max_depth'],
verbosity=0,
use_label_encoder=False,
eval_metric='mlogloss'
)
results['XGBoost'] = evaluate_model('XGBoost', xgb_model, X_train, X_test, y_train, y_test)
# Print results
print(f"\n{'Model':<12} {'Accuracy':>10} {'F1':>10} {'Train(s)':>10} {'Infer(s)':>10}")
print('-' * 55)
for model_name, metrics in results.items():
if metrics is not None:
print(f"{model_name:<12} {metrics['accuracy']:>10.4f} {metrics['f1']:>10.4f} "
f"{metrics['train_time']:>10.4f} {metrics['inference_time']:>10.4f}")
return results
def main():
print("="*70)
print("TurboCat Multiclass Benchmark")
print(f"Comparing: TurboCat", end='')
if HAS_CATBOOST: print(", CatBoost", end='')
if HAS_LIGHTGBM: print(", LightGBM", end='')
if HAS_XGBOOST: print(", XGBoost", end='')
print(f"\nHyperparameters: {COMMON_PARAMS}")
print("="*70)
all_results = {}
# sklearn multiclass datasets
print("\n\n" + "#"*70)
print("# MULTICLASS DATASETS")
print("#"*70)
# Iris (3 classes)
iris = load_iris()
all_results['iris'] = run_benchmark('Iris (3 classes)', iris.data, iris.target)
# Wine (3 classes)
wine = load_wine()
all_results['wine'] = run_benchmark('Wine (3 classes)', wine.data, wine.target)
# Digits (10 classes)
digits = load_digits()
all_results['digits'] = run_benchmark('Digits (10 classes)', digits.data, digits.target)
# Synthetic 5 classes
X, y = make_classification(
n_samples=2000, n_features=20, n_informative=15,
n_redundant=3, n_classes=5, n_clusters_per_class=2, random_state=42
)
all_results['synthetic_5'] = run_benchmark('Synthetic (5 classes)', X, y)
# Synthetic 10 classes
X, y = make_classification(
n_samples=5000, n_features=30, n_informative=20,
n_redundant=5, n_classes=10, n_clusters_per_class=1, random_state=42
)
all_results['synthetic_10'] = run_benchmark('Synthetic (10 classes)', X, y)
# Summary
print("\n\n" + "="*70)
print("SUMMARY")
print("="*70)
models = ['TurboCat']
if HAS_CATBOOST: models.append('CatBoost')
if HAS_LIGHTGBM: models.append('LightGBM')
if HAS_XGBOOST: models.append('XGBoost')
# Aggregate metrics
agg = {m: {'acc': [], 'f1': [], 'train': [], 'infer': []} for m in models}
for name, result in all_results.items():
for m in models:
if result.get(m) is not None:
agg[m]['acc'].append(result[m]['accuracy'])
agg[m]['f1'].append(result[m]['f1'])
agg[m]['train'].append(result[m]['train_time'])
agg[m]['infer'].append(result[m]['inference_time'])
print(f"\n{'Model':<12} {'Avg Acc':>10} {'Avg F1':>10} {'Avg Train':>12} {'Speedup':>10}")
print('-' * 60)
baseline_train = np.mean(agg['CatBoost']['train']) if HAS_CATBOOST else 1.0
for m in models:
if agg[m]['acc']:
avg_acc = np.mean(agg[m]['acc'])
avg_f1 = np.mean(agg[m]['f1'])
avg_train = np.mean(agg[m]['train'])
speedup = baseline_train / avg_train if avg_train > 0 else 0
print(f"{m:<12} {avg_acc:>10.4f} {avg_f1:>10.4f} {avg_train:>12.4f} {speedup:>10.1f}x")
if __name__ == '__main__':
main()