Datasets:
File size: 11,874 Bytes
ac53f17 | 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 | """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()
|