def conteos(y_true, y_pred):
vn, fp, fn, vp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
return {"VN": int(vn), "FP": int(fp), "FN": int(fn), "VP": int(vp)}
def ficha_clf(y_true, y_pred, etiqueta, y_score=None):
prev = float(np.mean(y_true))
fila = {
"modelo": etiqueta,
"prevalencia": prev,
"exactitud": accuracy_score(y_true, y_pred),
"precisión": 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),
}
if y_score is not None:
fila["AUC"] = roc_auc_score(y_true, y_score)
fila["AP"] = average_precision_score(y_true, y_score)
return fila
def graficar_matriz(y_true, y_pred, titulo):
M = confusion_matrix(y_true, y_pred, labels=[0, 1])
fig, ax = plt.subplots(figsize=(4.6, 4.0))
im = ax.imshow(M, cmap="Blues")
ax.set_xticks([0, 1], ["ŷ = 0", "ŷ = 1"])
ax.set_yticks([0, 1], ["y = 0", "y = 1"])
for (i, j), val in np.ndenumerate(M):
ax.text(j, i, str(val), ha="center", va="center", fontsize=14, color="0.1")
ax.set_title(titulo)
fig.colorbar(im, ax=ax, fraction=0.046)
plt.tight_layout()
plt.show()
return M
def graficar_roc_pr(y_true, y_score, titulo):
fpr, tpr, _ = roc_curve(y_true, y_score)
p, r, _ = precision_recall_curve(y_true, y_score)
auc = roc_auc_score(y_true, y_score)
ap = average_precision_score(y_true, y_score)
prev = float(np.mean(y_true))
fig, axes = plt.subplots(1, 2, figsize=(9.4, 3.9))
axes[0].plot(fpr, tpr, label=f"AUC = {auc:.3f}")
axes[0].plot([0, 1], [0, 1], linestyle="--", color="0.5", label="azar")
axes[0].set_xlabel("FPR")
axes[0].set_ylabel("TPR (recall)")
axes[0].set_title("ROC")
axes[0].legend(fontsize=8)
axes[1].plot(r, p, label=f"AP = {ap:.3f}")
axes[1].axhline(prev, color="0.5", linestyle="--", label=f"baseline PR = {prev:.3f}")
axes[1].set_xlabel("recall")
axes[1].set_ylabel("precisión")
axes[1].set_title("Precisión–recall")
axes[1].set_ylim(-0.05, 1.05)
axes[1].legend(fontsize=8)
fig.suptitle(titulo, y=1.02)
plt.tight_layout()
plt.show()
def graficar_umbral(y_true, y_score, titulo):
taus = np.linspace(0.05, 0.95, 19)
filas = []
for t in taus:
yp = (y_score >= t).astype(int)
filas.append(
{
"τ": t,
"precisión": precision_score(y_true, yp, zero_division=0),
"recall": recall_score(y_true, yp, zero_division=0),
"F1": f1_score(y_true, yp, zero_division=0),
"exactitud": accuracy_score(y_true, yp),
}
)
df = pd.DataFrame(filas)
fig, ax = plt.subplots(figsize=(8.2, 4.2))
ax.plot(df["τ"], df["precisión"], marker="o", label="precisión")
ax.plot(df["τ"], df["recall"], marker="s", label="recall")
ax.plot(df["τ"], df["F1"], marker="^", label="F1")
ax.axvline(0.5, color="0.4", linestyle=":", label="τ = 0.5")
ax.set_xlabel("umbral τ")
ax.set_ylabel("métrica")
ax.set_title(titulo)
ax.legend(fontsize=8)
plt.tight_layout()
plt.show()
return df