"""Compare classifier architectures on the ViT-L/14 features. Conservative resource usage — single-threaded, sequential, no large ensembles. """ import pickle import json import warnings import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from pathlib import Path from sklearn.model_selection import StratifiedKFold, train_test_split from sklearn.linear_model import LogisticRegression from sklearn.neural_network import MLPClassifier from sklearn.ensemble import HistGradientBoostingClassifier from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.metrics import ( roc_auc_score, average_precision_score, roc_curve, precision_recall_curve, f1_score, accuracy_score, ) warnings.filterwarnings("ignore") OUT_DIR = Path(__file__).parent DATA_PATH = Path( "/home/jroth/photograph_detector/scripts/outputs/" "extract_openai_vitl14_features/clip_vitl14_features_labeled.pkl" ) N_FOLDS = 5 RANDOM_STATE = 42 def get_classifiers(): """Conservative set of classifiers — no n_jobs, modest sizes.""" return { "LogReg (C=0.1)": Pipeline([ ("scaler", StandardScaler()), ("clf", LogisticRegression(C=0.1, max_iter=1000, random_state=RANDOM_STATE)), ]), "LogReg (C=1)": Pipeline([ ("scaler", StandardScaler()), ("clf", LogisticRegression(C=1.0, max_iter=1000, random_state=RANDOM_STATE)), ]), "LogReg (C=10)": Pipeline([ ("scaler", StandardScaler()), ("clf", LogisticRegression(C=10.0, max_iter=1000, random_state=RANDOM_STATE)), ]), "MLP (256)": Pipeline([ ("scaler", StandardScaler()), ("clf", MLPClassifier( hidden_layer_sizes=(256,), max_iter=300, early_stopping=True, validation_fraction=0.1, random_state=RANDOM_STATE, )), ]), "MLP (512, 256)": Pipeline([ ("scaler", StandardScaler()), ("clf", MLPClassifier( hidden_layer_sizes=(512, 256), max_iter=300, early_stopping=True, validation_fraction=0.1, random_state=RANDOM_STATE, )), ]), "MLP (512, 256, 128)": Pipeline([ ("scaler", StandardScaler()), ("clf", MLPClassifier( hidden_layer_sizes=(512, 256, 128), max_iter=300, early_stopping=True, validation_fraction=0.1, random_state=RANDOM_STATE, )), ]), "MLP (256, alpha=1e-3)": Pipeline([ ("scaler", StandardScaler()), ("clf", MLPClassifier( hidden_layer_sizes=(256,), max_iter=300, early_stopping=True, validation_fraction=0.1, alpha=1e-3, random_state=RANDOM_STATE, )), ]), "HistGBM (100, d5)": HistGradientBoostingClassifier( max_iter=100, max_depth=5, learning_rate=0.1, early_stopping=True, validation_fraction=0.1, random_state=RANDOM_STATE, ), "HistGBM (300, d6)": HistGradientBoostingClassifier( max_iter=300, max_depth=6, learning_rate=0.05, early_stopping=True, validation_fraction=0.1, random_state=RANDOM_STATE, ), } def manual_cv(clf_factory, X, y, n_folds=N_FOLDS): """Run CV manually one fold at a time to keep memory low.""" cv = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=RANDOM_STATE) fold_metrics = [] for fold, (train_idx, val_idx) in enumerate(cv.split(X, y)): clf = clf_factory() clf.fit(X[train_idx], y[train_idx]) probs = clf.predict_proba(X[val_idx])[:, 1] preds = (probs >= 0.5).astype(int) fold_metrics.append({ "roc_auc": roc_auc_score(y[val_idx], probs), "avg_precision": average_precision_score(y[val_idx], probs), "accuracy": accuracy_score(y[val_idx], preds), "f1": f1_score(y[val_idx], preds), }) del clf # free memory between folds return { metric: { "mean": float(np.mean([f[metric] for f in fold_metrics])), "std": float(np.std([f[metric] for f in fold_metrics])), } for metric in ["roc_auc", "avg_precision", "accuracy", "f1"] } def main(): print("=" * 70) print("CLASSIFIER COMPARISON ON VIT-L/14 FEATURES") print("=" * 70) with open(DATA_PATH, "rb") as f: data = pickle.load(f) X = data["features"] y = data["labels"] print(f"Dataset: {X.shape[0]} samples, {X.shape[1]} features") print(f"Labels: {dict(zip(*np.unique(y, return_counts=True)))}") X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=RANDOM_STATE, stratify=y, ) print(f"Train: {len(y_train)}, Test: {len(y_test)}") classifiers = get_classifiers() # --- Phase 1: Cross-validation --- print(f"\nPHASE 1: {N_FOLDS}-fold CV (sequential, single-threaded)") print("-" * 70) cv_results = {} for name, clf_template in classifiers.items(): print(f" {name}...", end="", flush=True) try: # Create a factory that returns a fresh clone each fold from sklearn.base import clone factory = lambda t=clf_template: clone(t) result = manual_cv(factory, X_train, y_train) cv_results[name] = result print(f" AUC={result['roc_auc']['mean']:.4f} +/- {result['roc_auc']['std']:.4f}") except Exception as e: print(f" FAILED: {e}") cv_results[name] = {"error": str(e)} # --- Phase 2: Holdout eval for curves --- print(f"\nPHASE 2: Holdout evaluation") print("-" * 70) holdout_results = {} for name, clf in classifiers.items(): if "error" in cv_results.get(name, {}): continue print(f" {name}...", end="", flush=True) try: from sklearn.base import clone clf = clone(clf) clf.fit(X_train, y_train) probs = clf.predict_proba(X_test)[:, 1] fpr, tpr, _ = roc_curve(y_test, probs) prec, rec, _ = precision_recall_curve(y_test, probs) holdout_results[name] = { "roc_auc": float(roc_auc_score(y_test, probs)), "avg_precision": float(average_precision_score(y_test, probs)), "fpr": fpr, "tpr": tpr, "precision": prec, "recall": rec, } print(f" AUC={holdout_results[name]['roc_auc']:.4f}") del clf except Exception as e: print(f" FAILED: {e}") # --- Phase 3: Plots --- print(f"\nPHASE 3: Plots") print("-" * 70) valid = {k: v for k, v in cv_results.items() if "error" not in v} names = sorted(valid.keys(), key=lambda k: valid[k]["roc_auc"]["mean"], reverse=True) means = [valid[n]["roc_auc"]["mean"] for n in names] stds = [valid[n]["roc_auc"]["std"] for n in names] colors = ["#e74c3c" if "LogReg" in n else "#3498db" if "MLP" in n else "#2ecc71" for n in names] # Bar chart fig, ax = plt.subplots(figsize=(10, 5)) ax.barh(range(len(names)), means, xerr=stds, color=colors, alpha=0.8, edgecolor="white", linewidth=0.5, capsize=3) ax.set_yticks(range(len(names))) ax.set_yticklabels(names, fontsize=10) ax.set_xlabel("ROC AUC (5-fold CV)", fontsize=12) ax.set_title("Classifier Comparison on ViT-L/14 Features", fontsize=13) ax.grid(axis="x", alpha=0.3) ax.invert_yaxis() for i, (m, s) in enumerate(zip(means, stds)): ax.text(m + s + 0.002, i, f"{m:.4f}", va="center", fontsize=9) fig.tight_layout() fig.savefig(OUT_DIR / "classifier_comparison_auc.png", dpi=200, bbox_inches="tight") plt.close() print(" Saved classifier_comparison_auc.png") # All metrics metrics = ["roc_auc", "avg_precision", "accuracy", "f1"] metric_labels = ["ROC AUC", "Avg Precision", "Accuracy", "F1"] fig, axes = plt.subplots(1, 4, figsize=(18, 5), sharey=True) for ax, metric, label in zip(axes, metrics, metric_labels): m_means = [valid[n][metric]["mean"] for n in names] m_stds = [valid[n][metric]["std"] for n in names] ax.barh(range(len(names)), m_means, xerr=m_stds, color=colors, alpha=0.8, edgecolor="white", linewidth=0.5, capsize=3) ax.set_xlabel(label, fontsize=11) ax.grid(axis="x", alpha=0.3) ax.invert_yaxis() for i, (m, s) in enumerate(zip(m_means, m_stds)): ax.text(m + s + 0.002, i, f"{m:.3f}", va="center", fontsize=8) axes[0].set_yticks(range(len(names))) axes[0].set_yticklabels(names, fontsize=10) fig.suptitle("All Metrics (5-fold CV)", fontsize=13, y=1.01) fig.tight_layout() fig.savefig(OUT_DIR / "classifier_comparison_all_metrics.png", dpi=200, bbox_inches="tight") plt.close() print(" Saved classifier_comparison_all_metrics.png") # ROC + PR curves if holdout_results: fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6)) sorted_h = sorted(holdout_results.items(), key=lambda x: x[1]["roc_auc"], reverse=True) cmap = plt.cm.tab10(np.linspace(0, 1, len(sorted_h))) for i, (name, res) in enumerate(sorted_h): ax1.plot(res["fpr"], res["tpr"], color=cmap[i], lw=1.5, label=f'{name} ({res["roc_auc"]:.3f})') ax2.plot(res["recall"], res["precision"], color=cmap[i], lw=1.5, label=f'{name} ({res["avg_precision"]:.3f})') ax1.plot([0, 1], [0, 1], "k--", lw=1, alpha=0.3) ax1.set_xlabel("FPR"); ax1.set_ylabel("TPR") ax1.set_title("ROC Curves (holdout)"); ax1.legend(fontsize=8, loc="lower right") ax1.grid(alpha=0.3) ax2.set_xlabel("Recall"); ax2.set_ylabel("Precision") ax2.set_title("PR Curves (holdout)"); ax2.legend(fontsize=8, loc="lower left") ax2.grid(alpha=0.3) fig.tight_layout() fig.savefig(OUT_DIR / "classifier_comparison_curves.png", dpi=200, bbox_inches="tight") plt.close() print(" Saved classifier_comparison_curves.png") # --- Summary --- print(f"\n{'=' * 70}") print("SUMMARY (sorted by CV ROC AUC)") print(f"{'=' * 70}") print(f"{'Classifier':<25} {'CV AUC':>15} {'CV AP':>15} {'CV Acc':>15} {'Holdout AUC':>12}") print("-" * 80) for name in names: cv = valid[name] h_auc = holdout_results.get(name, {}).get("roc_auc", float("nan")) print(f"{name:<25} " f"{cv['roc_auc']['mean']:.4f}+/-{cv['roc_auc']['std']:.4f} " f"{cv['avg_precision']['mean']:.4f}+/-{cv['avg_precision']['std']:.4f} " f"{cv['accuracy']['mean']:.4f}+/-{cv['accuracy']['std']:.4f} " f"{h_auc:>10.4f}") # Save JSON save_results = {} for name in names: cv = valid[name] h = holdout_results.get(name, {}) save_results[name] = { "cv": {m: {"mean": cv[m]["mean"], "std": cv[m]["std"]} for m in ["roc_auc", "avg_precision", "accuracy", "f1"]}, "holdout": {"roc_auc": h.get("roc_auc"), "avg_precision": h.get("avg_precision")}, } with open(OUT_DIR / "classifier_comparison_results.json", "w") as f: json.dump(save_results, f, indent=2) print(f"\nSaved classifier_comparison_results.json") best = names[0] baseline_auc = valid["LogReg (C=1)"]["roc_auc"]["mean"] best_auc = valid[best]["roc_auc"]["mean"] print(f"\nBaseline LogReg (C=1) AUC: {baseline_auc:.4f}") print(f"Best: {best} (AUC: {best_auc:.4f}, delta: {best_auc - baseline_auc:+.4f})") if __name__ == "__main__": main()