Spaces:
Sleeping
Sleeping
feat: add TorchSklearnWrapper for PyTorch model compatibility with sklearn and enhance final model training process
Browse files
app/training/train_deep_classifiers.py
CHANGED
|
@@ -273,8 +273,129 @@ def evaluate_cv(
|
|
| 273 |
}
|
| 274 |
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
def main() -> None:
|
|
|
|
|
|
|
| 277 |
csv_path = sys.argv[1] if len(sys.argv) > 1 else "../DataSet/features.csv"
|
|
|
|
|
|
|
|
|
|
| 278 |
print(f"Device: {DEVICE}")
|
| 279 |
print(f"Loading: {csv_path}")
|
| 280 |
|
|
@@ -283,7 +404,7 @@ def main() -> None:
|
|
| 283 |
print(f"Samples: {len(y)}, Features: {n_features}")
|
| 284 |
print(f"AI: {np.sum(y == 1)}, Human: {np.sum(y == 0)}")
|
| 285 |
|
| 286 |
-
|
| 287 |
"Deep MLP (512-256-128-64)": DeepMLP,
|
| 288 |
"1D-CNN": Conv1DClassifier,
|
| 289 |
"Residual MLP (3 blocks)": ResidualMLP,
|
|
@@ -291,16 +412,24 @@ def main() -> None:
|
|
| 291 |
}
|
| 292 |
|
| 293 |
all_results = {}
|
| 294 |
-
for name, cls in
|
| 295 |
print(f"\n{'='*60}")
|
| 296 |
print(f" {name}")
|
| 297 |
print(f"{'='*60}")
|
| 298 |
result = evaluate_cv(cls, X, y, n_features)
|
| 299 |
-
all_results[name] = result
|
| 300 |
print(f" => Acc={result['accuracy']:.4f} AUC={result['roc_auc']:.4f} "
|
| 301 |
f"F1={result['f1']:.4f} Time={result['train_time_sec']:.0f}s")
|
| 302 |
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
with open(out_path, "w") as f:
|
| 305 |
json.dump(all_results, f, indent=2)
|
| 306 |
print(f"\nResults saved: {out_path}")
|
|
|
|
| 273 |
}
|
| 274 |
|
| 275 |
|
| 276 |
+
class TorchSklearnWrapper:
|
| 277 |
+
"""
|
| 278 |
+
Sklearn-compatible wrapper for trained PyTorch classifiers.
|
| 279 |
+
Saves model class name + state dict so it can be pickled and reloaded.
|
| 280 |
+
"""
|
| 281 |
+
|
| 282 |
+
def __init__(
|
| 283 |
+
self,
|
| 284 |
+
model_class: type,
|
| 285 |
+
n_features: int,
|
| 286 |
+
state_dict: dict,
|
| 287 |
+
scaler: StandardScaler,
|
| 288 |
+
) -> None:
|
| 289 |
+
self.model_class_name = model_class.__name__
|
| 290 |
+
self._model_class = model_class
|
| 291 |
+
self.n_features = n_features
|
| 292 |
+
self.state_dict = state_dict
|
| 293 |
+
self.scaler = scaler
|
| 294 |
+
self.n_features_in_ = n_features
|
| 295 |
+
|
| 296 |
+
def _build_model(self) -> nn.Module:
|
| 297 |
+
model = self._model_class(self.n_features)
|
| 298 |
+
model.load_state_dict(self.state_dict)
|
| 299 |
+
model.eval()
|
| 300 |
+
return model
|
| 301 |
+
|
| 302 |
+
def predict_proba(self, X: np.ndarray) -> np.ndarray:
|
| 303 |
+
model = self._build_model().to("cpu")
|
| 304 |
+
X_scaled = self.scaler.transform(X)
|
| 305 |
+
x_t = torch.tensor(X_scaled, dtype=torch.float32)
|
| 306 |
+
with torch.no_grad():
|
| 307 |
+
logits = model(x_t)
|
| 308 |
+
probs = torch.sigmoid(logits).numpy().flatten()
|
| 309 |
+
return np.column_stack([1.0 - probs, probs])
|
| 310 |
+
|
| 311 |
+
def __getstate__(self) -> dict:
|
| 312 |
+
state = self.__dict__.copy()
|
| 313 |
+
state.pop("_model_class", None)
|
| 314 |
+
return state
|
| 315 |
+
|
| 316 |
+
def __setstate__(self, state: dict) -> None:
|
| 317 |
+
self.__dict__.update(state)
|
| 318 |
+
# Re-attach class from global lookup
|
| 319 |
+
_CLASS_MAP = {
|
| 320 |
+
"DeepMLP": DeepMLP,
|
| 321 |
+
"Conv1DClassifier": Conv1DClassifier,
|
| 322 |
+
"ResidualMLP": ResidualMLP,
|
| 323 |
+
"AttentionMLP": AttentionMLP,
|
| 324 |
+
}
|
| 325 |
+
self._model_class = _CLASS_MAP.get(self.model_class_name, DeepMLP)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def train_final_model(
|
| 329 |
+
model_class: type,
|
| 330 |
+
X: np.ndarray,
|
| 331 |
+
y: np.ndarray,
|
| 332 |
+
epochs: int = EPOCHS,
|
| 333 |
+
patience: int = PATIENCE,
|
| 334 |
+
) -> TorchSklearnWrapper:
|
| 335 |
+
"""Train model on full dataset and return sklearn-compatible wrapper."""
|
| 336 |
+
from sklearn.model_selection import train_test_split
|
| 337 |
+
|
| 338 |
+
scaler = StandardScaler()
|
| 339 |
+
X_tr_raw, X_val_raw, y_tr, y_val = train_test_split(
|
| 340 |
+
X, y, test_size=0.1, stratify=y, random_state=SEED
|
| 341 |
+
)
|
| 342 |
+
X_tr = scaler.fit_transform(X_tr_raw)
|
| 343 |
+
X_v = scaler.transform(X_val_raw)
|
| 344 |
+
|
| 345 |
+
n_features = X.shape[1]
|
| 346 |
+
model = model_class(n_features).to(DEVICE)
|
| 347 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4)
|
| 348 |
+
criterion = nn.BCEWithLogitsLoss()
|
| 349 |
+
loader = DataLoader(
|
| 350 |
+
TensorDataset(
|
| 351 |
+
torch.tensor(X_tr, dtype=torch.float32),
|
| 352 |
+
torch.tensor(y_tr, dtype=torch.float32),
|
| 353 |
+
),
|
| 354 |
+
batch_size=BATCH_SIZE,
|
| 355 |
+
shuffle=True,
|
| 356 |
+
)
|
| 357 |
+
val_X = torch.tensor(X_v, dtype=torch.float32).to(DEVICE)
|
| 358 |
+
val_y = torch.tensor(y_val, dtype=torch.float32)
|
| 359 |
+
|
| 360 |
+
best_auc = 0.0
|
| 361 |
+
best_state = None
|
| 362 |
+
patience_ctr = 0
|
| 363 |
+
|
| 364 |
+
for epoch in range(epochs):
|
| 365 |
+
model.train()
|
| 366 |
+
for bx, by in loader:
|
| 367 |
+
bx, by = bx.to(DEVICE), by.to(DEVICE)
|
| 368 |
+
optimizer.zero_grad()
|
| 369 |
+
criterion(model(bx), by).backward()
|
| 370 |
+
optimizer.step()
|
| 371 |
+
|
| 372 |
+
model.eval()
|
| 373 |
+
with torch.no_grad():
|
| 374 |
+
probs = torch.sigmoid(model(val_X)).cpu().numpy()
|
| 375 |
+
auc = roc_auc_score(val_y.numpy(), probs)
|
| 376 |
+
if auc > best_auc:
|
| 377 |
+
best_auc = auc
|
| 378 |
+
best_state = {k: v.cpu().clone() for k, v in model.state_dict().items()}
|
| 379 |
+
patience_ctr = 0
|
| 380 |
+
else:
|
| 381 |
+
patience_ctr += 1
|
| 382 |
+
if patience_ctr >= patience:
|
| 383 |
+
break
|
| 384 |
+
|
| 385 |
+
return TorchSklearnWrapper(model_class, n_features, best_state or model.state_dict(), scaler)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _safe_name(name: str) -> str:
|
| 389 |
+
return name.lower().replace(" ", "_").replace("(", "").replace(")", "").replace("-", "_")
|
| 390 |
+
|
| 391 |
+
|
| 392 |
def main() -> None:
|
| 393 |
+
import pickle
|
| 394 |
+
|
| 395 |
csv_path = sys.argv[1] if len(sys.argv) > 1 else "../DataSet/features.csv"
|
| 396 |
+
out_dir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("models")
|
| 397 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 398 |
+
|
| 399 |
print(f"Device: {DEVICE}")
|
| 400 |
print(f"Loading: {csv_path}")
|
| 401 |
|
|
|
|
| 404 |
print(f"Samples: {len(y)}, Features: {n_features}")
|
| 405 |
print(f"AI: {np.sum(y == 1)}, Human: {np.sum(y == 0)}")
|
| 406 |
|
| 407 |
+
model_classes = {
|
| 408 |
"Deep MLP (512-256-128-64)": DeepMLP,
|
| 409 |
"1D-CNN": Conv1DClassifier,
|
| 410 |
"Residual MLP (3 blocks)": ResidualMLP,
|
|
|
|
| 412 |
}
|
| 413 |
|
| 414 |
all_results = {}
|
| 415 |
+
for name, cls in model_classes.items():
|
| 416 |
print(f"\n{'='*60}")
|
| 417 |
print(f" {name}")
|
| 418 |
print(f"{'='*60}")
|
| 419 |
result = evaluate_cv(cls, X, y, n_features)
|
| 420 |
+
all_results[name] = {**result, "type": "deep_learning"}
|
| 421 |
print(f" => Acc={result['accuracy']:.4f} AUC={result['roc_auc']:.4f} "
|
| 422 |
f"F1={result['f1']:.4f} Time={result['train_time_sec']:.0f}s")
|
| 423 |
|
| 424 |
+
print(f" Training final model for {name}...")
|
| 425 |
+
wrapper = train_final_model(cls, X, y)
|
| 426 |
+
pkl_path = out_dir / f"model_dl_{_safe_name(name)}.pkl"
|
| 427 |
+
with open(pkl_path, "wb") as f:
|
| 428 |
+
pickle.dump(wrapper, f)
|
| 429 |
+
all_results[name]["model_path"] = str(pkl_path)
|
| 430 |
+
print(f" Saved: {pkl_path}")
|
| 431 |
+
|
| 432 |
+
out_path = out_dir / "deep_learning_results.json"
|
| 433 |
with open(out_path, "w") as f:
|
| 434 |
json.dump(all_results, f, indent=2)
|
| 435 |
print(f"\nResults saved: {out_path}")
|