adjusted the profiling pipelines: multipliers & (potential) founders, explorative analyses
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -0,0 +1,245 @@
|
||||
"""Metrics, plots and statistical model-comparison utilities."""
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.calibration import calibration_curve
|
||||
from sklearn.metrics import (
|
||||
accuracy_score,
|
||||
average_precision_score,
|
||||
brier_score_loss,
|
||||
confusion_matrix,
|
||||
f1_score,
|
||||
matthews_corrcoef,
|
||||
mean_absolute_error,
|
||||
precision_recall_curve,
|
||||
precision_score,
|
||||
r2_score,
|
||||
recall_score,
|
||||
roc_auc_score,
|
||||
roc_curve,
|
||||
root_mean_squared_error,
|
||||
)
|
||||
from sklearn.model_selection import StratifiedKFold
|
||||
from statsmodels.stats.contingency_tables import mcnemar
|
||||
|
||||
|
||||
def compute_metrics(y_true, y_pred, y_proba):
|
||||
return {
|
||||
"accuracy": accuracy_score(y_true, y_pred),
|
||||
"precision": precision_score(y_true, y_pred, zero_division=0),
|
||||
"recall": recall_score(y_true, y_pred, zero_division=0),
|
||||
"f1": f1_score(y_true, y_pred, zero_division=0),
|
||||
"roc_auc": roc_auc_score(y_true, y_proba),
|
||||
"pr_auc": average_precision_score(y_true, y_proba),
|
||||
"mcc": matthews_corrcoef(y_true, y_pred),
|
||||
"brier": brier_score_loss(y_true, y_proba),
|
||||
}
|
||||
|
||||
|
||||
def fit_and_evaluate(model, X_train, y_train, X_test, y_test, max_train_size=None, random_state=42):
|
||||
if max_train_size is not None and len(X_train) > max_train_size:
|
||||
rng = np.random.RandomState(random_state)
|
||||
idx = rng.choice(len(X_train), size=max_train_size, replace=False)
|
||||
X_train = X_train.iloc[idx] if hasattr(X_train, "iloc") else X_train[idx]
|
||||
y_train = y_train.iloc[idx] if hasattr(y_train, "iloc") else y_train[idx]
|
||||
|
||||
model.fit(X_train, y_train)
|
||||
proba = model.predict_proba(X_test)[:, 1]
|
||||
pred = (proba >= 0.5).astype(int)
|
||||
metrics = compute_metrics(y_test, pred, proba)
|
||||
return model, metrics, pred, proba
|
||||
|
||||
|
||||
def results_table(rows, sort_by="pr_auc"):
|
||||
"""`rows`: list of dicts, each with a 'model' key plus metric keys."""
|
||||
df = pd.DataFrame(rows).set_index("model")
|
||||
return df.sort_values(sort_by, ascending=False)
|
||||
|
||||
|
||||
def save_table(df, csv_path, md_path=None):
|
||||
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
df.to_csv(csv_path)
|
||||
if md_path is not None:
|
||||
md_path.write_text(df.to_markdown())
|
||||
|
||||
|
||||
def plot_confusion(y_true, y_pred, title, save_path):
|
||||
cm = confusion_matrix(y_true, y_pred)
|
||||
fig, ax = plt.subplots(figsize=(4, 4))
|
||||
ax.imshow(cm, cmap="Blues")
|
||||
for (i, j), v in np.ndenumerate(cm):
|
||||
ax.text(j, i, str(v), ha="center", va="center")
|
||||
ax.set_xticks([0, 1])
|
||||
ax.set_xticklabels(["non-founder", "founder"])
|
||||
ax.set_yticks([0, 1])
|
||||
ax.set_yticklabels(["non-founder", "founder"])
|
||||
ax.set_xlabel("Predicted")
|
||||
ax.set_ylabel("Actual")
|
||||
ax.set_title(title)
|
||||
save_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fig.tight_layout()
|
||||
fig.savefig(save_path, dpi=150)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def plot_roc_pr(curves, save_path_prefix):
|
||||
"""`curves`: dict[model_name] -> (y_true, y_proba)."""
|
||||
save_path_prefix.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
fig, ax = plt.subplots(figsize=(5, 5))
|
||||
for name, (y_true, y_proba) in curves.items():
|
||||
fpr, tpr, _ = roc_curve(y_true, y_proba)
|
||||
ax.plot(fpr, tpr, label=f"{name} (AUC={roc_auc_score(y_true, y_proba):.3f})")
|
||||
ax.plot([0, 1], [0, 1], "--", color="grey")
|
||||
ax.set_xlabel("False positive rate")
|
||||
ax.set_ylabel("True positive rate")
|
||||
ax.set_title("ROC curves")
|
||||
ax.legend(fontsize=8)
|
||||
fig.tight_layout()
|
||||
fig.savefig(f"{save_path_prefix}_roc.png", dpi=150)
|
||||
plt.close(fig)
|
||||
|
||||
fig, ax = plt.subplots(figsize=(5, 5))
|
||||
for name, (y_true, y_proba) in curves.items():
|
||||
precision, recall, _ = precision_recall_curve(y_true, y_proba)
|
||||
ax.plot(recall, precision, label=f"{name} (AP={average_precision_score(y_true, y_proba):.3f})")
|
||||
ax.set_xlabel("Recall")
|
||||
ax.set_ylabel("Precision")
|
||||
ax.set_title("Precision-Recall curves")
|
||||
ax.legend(fontsize=8)
|
||||
fig.tight_layout()
|
||||
fig.savefig(f"{save_path_prefix}_pr.png", dpi=150)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def mcnemar_test(y_true, pred_a, pred_b):
|
||||
y_true, pred_a, pred_b = np.asarray(y_true), np.asarray(pred_a), np.asarray(pred_b)
|
||||
a_correct = pred_a == y_true
|
||||
b_correct = pred_b == y_true
|
||||
table = [
|
||||
[np.sum(a_correct & b_correct), np.sum(a_correct & ~b_correct)],
|
||||
[np.sum(~a_correct & b_correct), np.sum(~a_correct & ~b_correct)],
|
||||
]
|
||||
result = mcnemar(table, exact=False, correction=True)
|
||||
return {"statistic": float(result.statistic), "p_value": float(result.pvalue)}
|
||||
|
||||
|
||||
def cross_validate_model(model_factory, X, y, cv=5, random_state=42):
|
||||
"""K-fold stratified CV, refitting a fresh model each fold via `model_factory()`
|
||||
(a zero-arg callable returning an unfitted estimator). Returns a DataFrame with
|
||||
one row per fold plus a final 'mean' row and a 95% CI (normal approximation
|
||||
across fold scores) for each metric."""
|
||||
skf = StratifiedKFold(n_splits=cv, shuffle=True, random_state=random_state)
|
||||
X_arr = X.reset_index(drop=True) if hasattr(X, "reset_index") else X
|
||||
y_arr = y.reset_index(drop=True) if hasattr(y, "reset_index") else y
|
||||
|
||||
fold_rows = []
|
||||
for fold, (train_idx, test_idx) in enumerate(skf.split(X_arr, y_arr)):
|
||||
model = model_factory()
|
||||
model.fit(X_arr.iloc[train_idx], y_arr.iloc[train_idx])
|
||||
proba = model.predict_proba(X_arr.iloc[test_idx])[:, 1]
|
||||
pred = (proba >= 0.5).astype(int)
|
||||
metrics = compute_metrics(y_arr.iloc[test_idx], pred, proba)
|
||||
fold_rows.append({"fold": fold, **metrics})
|
||||
|
||||
fold_df = pd.DataFrame(fold_rows).set_index("fold")
|
||||
n = len(fold_df)
|
||||
mean = fold_df.mean()
|
||||
std = fold_df.std(ddof=1)
|
||||
ci95 = 1.96 * std / np.sqrt(n)
|
||||
summary = pd.DataFrame({"mean": mean, "std": std, "ci95_low": mean - ci95, "ci95_high": mean + ci95})
|
||||
return fold_df, summary
|
||||
|
||||
|
||||
def bootstrap_metric_ci(y_true, y_proba, n_boot=1000, random_state=42, threshold=0.5):
|
||||
"""Percentile bootstrap CI (2.5/97.5%) for roc_auc/pr_auc/mcc/f1, resampling
|
||||
the held-out test set with replacement `n_boot` times."""
|
||||
y_true = np.asarray(y_true)
|
||||
y_proba = np.asarray(y_proba)
|
||||
rng = np.random.RandomState(random_state)
|
||||
n = len(y_true)
|
||||
boot_rows = []
|
||||
for _ in range(n_boot):
|
||||
idx = rng.randint(0, n, size=n)
|
||||
yt, yp = y_true[idx], y_proba[idx]
|
||||
if yt.sum() == 0 or yt.sum() == n:
|
||||
continue # a resample with only one class breaks roc_auc/pr_auc
|
||||
pred = (yp >= threshold).astype(int)
|
||||
boot_rows.append(compute_metrics(yt, pred, yp))
|
||||
|
||||
boot_df = pd.DataFrame(boot_rows)
|
||||
point = pd.Series(compute_metrics(y_true, (y_proba >= threshold).astype(int), y_proba))
|
||||
summary = pd.DataFrame(
|
||||
{
|
||||
"point_estimate": point,
|
||||
"ci95_low": boot_df.quantile(0.025),
|
||||
"ci95_high": boot_df.quantile(0.975),
|
||||
}
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def stratified_metrics(y_true, y_pred, y_proba, group):
|
||||
"""Break down `compute_metrics` by the values of `group`. All four arguments
|
||||
must be positionally aligned (same row order) -- pandas Index labels are
|
||||
ignored on purpose since y_pred/y_proba are typically plain numpy arrays
|
||||
with no meaningful index of their own."""
|
||||
y_true = np.asarray(y_true)
|
||||
y_pred = np.asarray(y_pred)
|
||||
y_proba = np.asarray(y_proba)
|
||||
group = np.asarray(group)
|
||||
|
||||
rows = []
|
||||
for value in pd.unique(group):
|
||||
mask = group == value
|
||||
yt, yp, ypr = y_true[mask], y_pred[mask], y_proba[mask]
|
||||
if len(np.unique(yt)) < 2:
|
||||
continue # AUC undefined with a single class present
|
||||
rows.append({"group": value, "n": int(mask.sum()), "founder_rate": float(yt.mean()), **compute_metrics(yt, yp, ypr)})
|
||||
return pd.DataFrame(rows).set_index("group").sort_values("n", ascending=False)
|
||||
|
||||
|
||||
def regression_metrics(y_true, y_pred):
|
||||
return {
|
||||
"mae": mean_absolute_error(y_true, y_pred),
|
||||
"rmse": root_mean_squared_error(y_true, y_pred),
|
||||
"r2": r2_score(y_true, y_pred),
|
||||
}
|
||||
|
||||
|
||||
def plot_predicted_vs_actual(curves, save_path):
|
||||
"""`curves`: dict[model_name] -> (y_true, y_pred), one scatter subplot each."""
|
||||
save_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
n = len(curves)
|
||||
fig, axes = plt.subplots(1, n, figsize=(4 * n, 4), sharex=True, sharey=True)
|
||||
axes = np.atleast_1d(axes)
|
||||
for ax, (name, (y_true, y_pred)) in zip(axes, curves.items()):
|
||||
ax.scatter(y_true, y_pred, alpha=0.3, s=10)
|
||||
lims = [min(np.min(y_true), np.min(y_pred)), max(np.max(y_true), np.max(y_pred))]
|
||||
ax.plot(lims, lims, "--", color="grey")
|
||||
ax.set_xlabel("Actual founding_age")
|
||||
ax.set_ylabel("Predicted founding_age")
|
||||
ax.set_title(name)
|
||||
fig.tight_layout()
|
||||
fig.savefig(save_path, dpi=150)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def plot_calibration(curves, save_path, n_bins=10):
|
||||
"""`curves`: dict[model_name] -> (y_true, y_proba). Reliability diagram."""
|
||||
save_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fig, ax = plt.subplots(figsize=(5, 5))
|
||||
ax.plot([0, 1], [0, 1], "--", color="grey", label="perfectly calibrated")
|
||||
for name, (y_true, y_proba) in curves.items():
|
||||
frac_pos, mean_pred = calibration_curve(y_true, y_proba, n_bins=n_bins, strategy="quantile")
|
||||
ax.plot(mean_pred, frac_pos, marker="o", label=name)
|
||||
ax.set_xlabel("Mean predicted probability")
|
||||
ax.set_ylabel("Fraction of positives")
|
||||
ax.set_title("Calibration (reliability diagram)")
|
||||
ax.legend(fontsize=8)
|
||||
fig.tight_layout()
|
||||
fig.savefig(save_path, dpi=150)
|
||||
plt.close(fig)
|
||||
Reference in New Issue
Block a user