OncomIA01
Merge ST into single block (20 medium-low Qs), remove Transformer/foundation model Qs, prune non-contextual graphics
e735979 Download app.py from OncomIA01/IAtest: direct link, hf CLI and curl.
- Browser
- Download file 47.9 kB
-
https://huggingface.co/spaces/OncomIA01/IAtest/resolve/main/app.py
- Command line
-
hf download hf://spaces/OncomIA01/IAtest/app.py
-
curl -L -o app.py https://huggingface.co/spaces/OncomIA01/IAtest/resolve/main/app.py
47.9 kB
# -*- coding: utf-8 -*-
"""Banco de Examen IA - Streamlit App (UAX, Ingenieria Matematica).
Modos:
- Examen rapido: 20 preguntas aleatorias.
- Examen medio: 50 preguntas aleatorias.
- Modo estudio: las 225 preguntas en orden.
- Por bloque: selecciona uno o varios bloques tematicos.
Cada pregunta puede llevar un grafico dinamico (matplotlib). El alumno
selecciona la opcion y pulsa "Mostrar respuesta" para ver la solucion,
la justificacion y la referencia exacta a la slide del PowerPoint.
"""
from __future__ import annotations
import json
import random
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import streamlit as st
# -----------------------------------------------------------------------------
# Iconos por bloque (emoji + color)
# -----------------------------------------------------------------------------
BLOQUE_ICONOS = {
"0. Conceptos basicos para empezar": "๐ฑ",
"1. Introduccion a la IA, historia y etica": "๐ค",
"2. Tipos de ML/DL y arquitectura de solucion": "๐ง ",
"3. EDA - Analisis Exploratorio de Datos": "๐",
"4. Evaluacion de modelos de clasificacion": "๐ฏ",
"5. Modelos de Clasificacion I": "๐ณ",
"6. Overfitting, Underfitting y Balanceo": "โ๏ธ",
"7. Evaluacion de modelos de regresion": "๐",
"8. Regresion lineal, no lineal y arboles": "๐",
"9. Ridge, Lasso y Regresion Logistica": "๐๏ธ",
"10. Redes Neuronales": "๐ฎ",
"11. Series Temporales": "โฑ๏ธ",
"13. Casos practicos avanzados de modelos y evaluacion": "๐",
}
# -----------------------------------------------------------------------------
# Carga de datos
# -----------------------------------------------------------------------------
@st.cache_data
def cargar_preguntas() -> list[dict]:
ruta = Path(__file__).parent / "questions.json"
with ruta.open(encoding="utf-8") as f:
return json.load(f)
# -----------------------------------------------------------------------------
# Renderizado de graficos matplotlib
# -----------------------------------------------------------------------------
def _figura_roc(auc_objetivo: float):
fig, ax = plt.subplots(figsize=(4.8, 4.2))
fpr = np.linspace(0, 1, 200)
if abs(auc_objetivo - 0.5) < 1e-3:
tpr = fpr.copy()
else:
gamma = max(0.001, (1 - auc_objetivo) / max(auc_objetivo, 1e-3))
tpr = fpr ** gamma
ax.plot(fpr, tpr, lw=2.6, color="#1f77b4", label=f"Modelo (AUC~{auc_objetivo:.2f})")
ax.plot([0, 1], [0, 1], "--", color="grey", label="Azar (AUC=0.5)")
ax.set_xlabel("FPR (Falsos Positivos)", fontsize=11)
ax.set_ylabel("TPR (Recall / Sensibilidad)", fontsize=11)
ax.set_title("Curva ROC", fontsize=12, fontweight="bold")
ax.legend(loc="lower right", fontsize=9)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_loss(modo: str):
epochs = np.arange(1, 51)
fig, ax = plt.subplots(figsize=(4.8, 3.8))
if modo == "overfit":
train = 1.2 * np.exp(-epochs / 12) + 0.05
val = 1.2 * np.exp(-epochs / 10) + 0.05 + 0.4 * (1 - np.exp(-(epochs - 18).clip(0) / 12))
titulo = "Overfitting"
elif modo == "underfit":
train = 1.0 - 0.08 * np.tanh(epochs / 30) + 0.02 * np.random.RandomState(0).randn(len(epochs))
val = train + 0.04
titulo = "Underfitting"
else:
train = 0.9 * np.exp(-epochs / 10) + 0.1
val = 0.95 * np.exp(-epochs / 11) + 0.12
titulo = "Buen ajuste"
ax.plot(epochs, train, lw=2.4, label="Train loss", color="#1f77b4")
ax.plot(epochs, val, lw=2.4, label="Val loss", color="#ff7f0e")
ax.set_xlabel("Epoch", fontsize=11)
ax.set_ylabel("Loss", fontsize=11)
ax.set_title(f"Curva de perdida ({titulo})", fontsize=12, fontweight="bold")
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_learning_curve(modo: str):
n = np.linspace(50, 1500, 30)
fig, ax = plt.subplots(figsize=(4.8, 3.8))
if modo == "data_helps":
train = 0.1 + 0.05 * np.exp(-n / 2000)
val = 0.4 * np.exp(-n / 1200) + 0.12
elif modo == "plateau":
train = 0.35 + 0.0 * n
val = 0.38 + 0.0 * n
else:
train = 0.08 + 0.0 * n
val = 0.10 + 0.0 * n
ax.plot(n, 1 - train, lw=2.2, label="Train score", color="#1f77b4")
ax.plot(n, 1 - val, lw=2.2, label="Val score", color="#ff7f0e")
ax.set_xlabel("Tamano del conjunto de entrenamiento", fontsize=11)
ax.set_ylabel("Score", fontsize=11)
ax.set_title("Curva de aprendizaje", fontsize=12, fontweight="bold")
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_densidades(separacion: str):
fig, ax = plt.subplots(figsize=(4.8, 3.6))
x = np.linspace(-4, 6, 400)
if separacion == "alta":
d1 = np.exp(-(x + 1) ** 2 / 0.8)
d2 = np.exp(-(x - 4) ** 2 / 0.8)
umbral = 1.5
else:
d1 = np.exp(-x ** 2 / 1.2)
d2 = np.exp(-(x - 2) ** 2 / 1.2)
umbral = 1.0
ax.fill_between(x, d1, alpha=0.4, color="#1f77b4", label="Negativos")
ax.fill_between(x, d2, alpha=0.4, color="#d62728", label="Positivos")
ax.axvline(umbral, color="black", lw=2, ls="--", label=f"Umbral={umbral}")
ax.set_xlabel("Score", fontsize=11)
ax.set_ylabel("Densidad", fontsize=11)
ax.set_title("Densidades de clases", fontsize=12, fontweight="bold")
ax.legend(fontsize=9)
fig.tight_layout()
return fig
def _figura_kmeans():
rng = np.random.RandomState(7)
centros = np.array([[0, 0], [4, 4], [-3, 4]])
pts, labels = [], []
for k, c in enumerate(centros):
pts.append(rng.randn(60, 2) * 0.8 + c)
labels.extend([k] * 60)
X = np.vstack(pts)
labels = np.array(labels)
fig, ax = plt.subplots(figsize=(4.8, 3.8))
colores = ["#1f77b4", "#2ca02c", "#d62728"]
for k in range(3):
m = labels == k
ax.scatter(X[m, 0], X[m, 1], s=22, color=colores[k], alpha=0.7, label=f"Cluster {k}")
ax.scatter(centros[:, 0], centros[:, 1], s=200, marker="X", color="black", label="Centroides")
ax.set_title("K-Means con k=3", fontsize=12, fontweight="bold")
ax.legend(fontsize=9)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_elbow():
k = np.arange(1, 11)
inercia = 1000 * np.exp(-k / 2.0) + 80
fig, ax = plt.subplots(figsize=(4.8, 3.6))
ax.plot(k, inercia, "o-", lw=2.2, color="#1f77b4", markersize=8)
ax.axvline(3, ls="--", color="red", label="Codo en k=3")
ax.set_xlabel("Numero de clusters k", fontsize=11)
ax.set_ylabel("Inercia (WCSS)", fontsize=11)
ax.set_title("Metodo del codo", fontsize=12, fontweight="bold")
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_scree():
autovalores = np.array([5.2, 3.1, 1.4, 0.6, 0.3, 0.15, 0.08, 0.04])
fig, ax = plt.subplots(figsize=(4.8, 3.6))
ax.bar(np.arange(1, len(autovalores) + 1), autovalores, color="#1f77b4", alpha=0.75)
ax.plot(np.arange(1, len(autovalores) + 1), autovalores, "o-k", lw=1.8, markersize=8)
ax.set_xlabel("Componente principal", fontsize=11)
ax.set_ylabel("Autovalor (lambda)", fontsize=11)
ax.set_title("Scree Plot PCA", fontsize=12, fontweight="bold")
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_acf():
lags = np.arange(0, 16)
rho = 0.7 ** lags
fig, ax = plt.subplots(1, 2, figsize=(7.8, 3.4))
ax[0].vlines(lags, 0, rho, color="#1f77b4", lw=2.2)
ax[0].scatter(lags, rho, color="#1f77b4", s=30)
ax[0].axhline(0.0, color="black", lw=0.7)
ax[0].axhline(0.2, ls="--", color="grey")
ax[0].axhline(-0.2, ls="--", color="grey")
ax[0].set_title("ACF (AR(1))", fontsize=11, fontweight="bold")
ax[0].set_xlabel("Lag")
pacf = np.zeros_like(lags, dtype=float)
pacf[1] = 0.7
ax[1].vlines(lags, 0, pacf, color="#d62728", lw=2.2)
ax[1].scatter(lags, pacf, color="#d62728", s=30)
ax[1].axhline(0.0, color="black", lw=0.7)
ax[1].axhline(0.2, ls="--", color="grey")
ax[1].axhline(-0.2, ls="--", color="grey")
ax[1].set_title("PACF (AR(1))", fontsize=11, fontweight="bold")
ax[1].set_xlabel("Lag")
fig.tight_layout()
return fig
def _figura_confusion(tp, fn, fp, tn):
fig, ax = plt.subplots(figsize=(4.8, 4.0))
matriz = np.array([[tp, fn], [fp, tn]])
im = ax.imshow(matriz, cmap="Blues")
ax.set_xticks([0, 1])
ax.set_yticks([0, 1])
ax.set_xticklabels(["Predicho +", "Predicho -"], fontsize=10)
ax.set_yticklabels(["Real +", "Real -"], fontsize=10)
for i in range(2):
for j in range(2):
v = matriz[i, j]
color = "white" if v > matriz.max() / 2 else "black"
etiq = ["TP", "FN", "FP", "TN"][i * 2 + j]
ax.text(j, i, f"{etiq}\n{v}", ha="center", va="center",
color=color, fontsize=13, fontweight="bold")
ax.set_title("Matriz de confusion", fontsize=12, fontweight="bold")
fig.colorbar(im, ax=ax, fraction=0.04)
fig.tight_layout()
return fig
def _figura_perceptron():
fig, ax = plt.subplots(figsize=(5.8, 3.8))
ax.set_xlim(0, 10)
ax.set_ylim(0, 6)
ax.axis("off")
entradas_y = [4.8, 3.6, 2.4, 1.2]
etiquetas = ["x1", "x2", "x3", "bias"]
for y, lab in zip(entradas_y, etiquetas):
ax.add_patch(plt.Circle((1.5, y), 0.38, fc="#cfe2f3", ec="black"))
ax.text(1.5, y, lab, ha="center", va="center", fontsize=11)
ax.add_patch(plt.Circle((6, 3), 0.6, fc="#f9cb9c", ec="black"))
ax.text(6, 3, "ฮฃ\n f", ha="center", va="center", fontsize=12)
ax.add_patch(plt.Circle((9, 3), 0.38, fc="#b6d7a8", ec="black"))
ax.text(9, 3, "y", ha="center", va="center", fontsize=11)
pesos = ["w1", "w2", "w3", "w0"]
for y, w in zip(entradas_y, pesos):
ax.annotate("", xy=(5.5, 3), xytext=(1.85, y),
arrowprops=dict(arrowstyle="->", color="grey", lw=1.3))
ax.text(3.6, (y + 3) / 2, w, fontsize=10, color="black",
bbox=dict(boxstyle="round,pad=0.1", fc="white", ec="grey"))
ax.annotate("", xy=(8.65, 3), xytext=(6.6, 3),
arrowprops=dict(arrowstyle="->", color="grey", lw=1.5))
ax.text(7.6, 3.2, "salida", fontsize=10)
ax.set_title("Esquema del perceptron", fontsize=12, fontweight="bold")
fig.tight_layout()
return fig
def _figura_red_neuronal():
fig, ax = plt.subplots(figsize=(6.6, 4.2))
ax.set_xlim(0, 10)
ax.set_ylim(0, 6)
ax.axis("off")
capas = [(1.2, 4, ["x1", "x2", "x3"]),
(4.0, 5, ["h1", "h2", "h3", "h4", "h5"]),
(6.8, 4, ["h1", "h2", "h3", "h4"]),
(9.2, 2, ["y1", "y2"])]
colores = ["#cfe2f3", "#f9cb9c", "#f9cb9c", "#b6d7a8"]
titulos = ["Input", "Hidden 1", "Hidden 2", "Output"]
posiciones = []
for (x, n, etiq), color, titulo in zip(capas, colores, titulos):
ys = np.linspace(5.4, 0.6, n)
pos = []
for y, e in zip(ys, etiq):
ax.add_patch(plt.Circle((x, y), 0.30, fc=color, ec="black"))
ax.text(x, y, e, ha="center", va="center", fontsize=9)
pos.append((x, y))
ax.text(x, 5.85, titulo, ha="center", fontsize=10, fontweight="bold")
posiciones.append(pos)
for cap1, cap2 in zip(posiciones, posiciones[1:]):
for (x1, y1) in cap1:
for (x2, y2) in cap2:
ax.plot([x1, x2], [y1, y2], color="grey", lw=0.5, alpha=0.6)
ax.set_title("Red neuronal multicapa", fontsize=12, fontweight="bold")
fig.tight_layout()
return fig
def _figura_activaciones():
x = np.linspace(-6, 6, 400)
fig, ax = plt.subplots(figsize=(5.8, 3.8))
ax.plot(x, 1 / (1 + np.exp(-x)), label="Sigmoide", color="#1f77b4", lw=2.4)
ax.plot(x, np.tanh(x), label="Tanh", color="#ff7f0e", lw=2.4)
ax.plot(x, np.maximum(0, x) / 4, label="ReLU (/4)", color="#2ca02c", lw=2.4)
ax.plot(x, np.log1p(np.exp(x)) / 4, label="Softplus (/4)", color="#9467bd", lw=2.4)
ax.axhline(0, color="black", lw=0.5)
ax.axvline(0, color="black", lw=0.5)
ax.set_title("Funciones de activacion", fontsize=12, fontweight="bold")
ax.set_xlabel("z", fontsize=11)
ax.set_ylabel("f(z)", fontsize=11)
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_sigmoid_logistic():
x = np.linspace(-6, 6, 400)
p = 1 / (1 + np.exp(-x))
fig, ax = plt.subplots(figsize=(5.2, 3.6))
ax.plot(x, p, color="#1f77b4", lw=2.4)
ax.axhline(0.5, ls="--", color="red", label="umbral 0.5")
ax.axhline(0, color="black", lw=0.5)
ax.fill_between(x, 0, p, where=(p > 0.5), alpha=0.2, color="green", label="clase 1")
ax.fill_between(x, 0, p, where=(p <= 0.5), alpha=0.2, color="orange", label="clase 0")
ax.set_title("Regresion logistica: p=1/(1+e^-z)", fontsize=12, fontweight="bold")
ax.set_xlabel("z = beta0 + betaยทx", fontsize=11)
ax.set_ylabel("Probabilidad", fontsize=11)
ax.legend(fontsize=9)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_bias_variance():
fig, axes = plt.subplots(1, 4, figsize=(8.8, 2.6))
rng = np.random.RandomState(0)
casos = [("Bajo sesgo\nBaja varianza", 0.0, 0.0, 0.10),
("Bajo sesgo\nAlta varianza", 0.0, 0.0, 0.45),
("Alto sesgo\nBaja varianza", 0.4, 0.2, 0.10),
("Alto sesgo\nAlta varianza", 0.4, 0.2, 0.45)]
for ax, (titulo, cx, cy, sd) in zip(axes, casos):
theta = np.linspace(0, 2 * np.pi, 100)
for r, col in [(1.0, "#cccccc"), (0.66, "#888888"), (0.33, "#444444")]:
ax.plot(r * np.cos(theta), r * np.sin(theta), color=col, lw=0.9)
pts = rng.randn(20, 2) * sd + np.array([cx, cy])
ax.scatter(pts[:, 0], pts[:, 1], color="#d62728", s=22)
ax.scatter([0], [0], color="black", marker="x", s=50)
ax.set_xlim(-1.2, 1.2)
ax.set_ylim(-1.2, 1.2)
ax.set_aspect("equal")
ax.axis("off")
ax.set_title(titulo, fontsize=9)
fig.suptitle("Sesgo vs Varianza", fontsize=12, fontweight="bold")
fig.tight_layout()
return fig
def _figura_decision_tree():
fig, ax = plt.subplots(figsize=(6.2, 3.8))
ax.set_xlim(0, 10)
ax.set_ylim(0, 6)
ax.axis("off")
nodos = {
"root": (5, 5, "X1 <= 2.5?"),
"L1": (2.5, 3.2, "X2 <= 1?"),
"R1": (7.5, 3.2, "Clase A"),
"L2": (1.3, 1.4, "Clase A"),
"R2": (3.7, 1.4, "Clase B"),
}
for k, (x, y, t) in nodos.items():
es_hoja = "Clase" in t
ax.add_patch(plt.Rectangle((x - 1.0, y - 0.38), 2.0, 0.76,
fc="#b6d7a8" if es_hoja else "#cfe2f3",
ec="black"))
ax.text(x, y, t, ha="center", va="center", fontsize=10)
aristas = [("root", "L1", "si"), ("root", "R1", "no"),
("L1", "L2", "si"), ("L1", "R2", "no")]
for a, b, lab in aristas:
x1, y1, _ = nodos[a]
x2, y2, _ = nodos[b]
ax.annotate("", xy=(x2, y2 + 0.38), xytext=(x1, y1 - 0.38),
arrowprops=dict(arrowstyle="->", color="grey", lw=1.4))
ax.text((x1 + x2) / 2 + 0.18, (y1 + y2) / 2, lab,
fontsize=9, color="grey")
ax.set_title("Arbol de decision", fontsize=12, fontweight="bold")
fig.tight_layout()
return fig
def _figura_bagging_vs_boosting():
fig, axes = plt.subplots(1, 2, figsize=(7.4, 3.4))
ax = axes[0]
ax.set_xlim(0, 10)
ax.set_ylim(0, 6)
ax.axis("off")
ax.set_title("Bagging (Random Forest)", fontsize=11, fontweight="bold")
ax.add_patch(plt.Rectangle((4, 4.6), 2, 0.7, fc="#cfe2f3", ec="black"))
ax.text(5, 4.95, "Dataset", ha="center", fontsize=10)
for k, x in enumerate([1.0, 3.5, 6.0, 8.5]):
ax.add_patch(plt.Rectangle((x, 2.6), 1.4, 0.7, fc="#b6d7a8", ec="black"))
ax.text(x + 0.7, 2.95, f"Arbol {k+1}", ha="center", fontsize=9)
ax.annotate("", xy=(x + 0.7, 3.3), xytext=(5, 4.6),
arrowprops=dict(arrowstyle="->", color="grey"))
ax.add_patch(plt.Rectangle((4, 0.8), 2, 0.7, fc="#f9cb9c", ec="black"))
ax.text(5, 1.15, "Promedio/Voto", ha="center", fontsize=10)
for x in [1.7, 4.2, 6.7, 9.2]:
ax.annotate("", xy=(5, 1.5), xytext=(x, 2.6),
arrowprops=dict(arrowstyle="->", color="grey", lw=0.7))
ax = axes[1]
ax.set_xlim(0, 10)
ax.set_ylim(0, 6)
ax.axis("off")
ax.set_title("Boosting (XGBoost/AdaBoost)", fontsize=11, fontweight="bold")
for k, x in enumerate([0.5, 3, 5.5, 8]):
ax.add_patch(plt.Rectangle((x, 2.6), 1.6, 0.7, fc="#b6d7a8", ec="black"))
ax.text(x + 0.8, 2.95, f"Arbol {k+1}", ha="center", fontsize=9)
for x1, x2 in [(2.1, 3), (4.6, 5.5), (7.1, 8)]:
ax.annotate("", xy=(x2, 2.95), xytext=(x1, 2.95),
arrowprops=dict(arrowstyle="->", color="red", lw=1.5))
ax.text(5, 1.6, "Cada arbol corrige errores del anterior",
ha="center", fontsize=9, color="red")
ax.add_patch(plt.Rectangle((3.8, 4.4), 2.4, 0.7, fc="#cfe2f3", ec="black"))
ax.text(5, 4.75, "Dataset", ha="center", fontsize=10)
ax.annotate("", xy=(1.3, 3.3), xytext=(5, 4.4),
arrowprops=dict(arrowstyle="->", color="grey"))
fig.tight_layout()
return fig
def _figura_histogram_kde():
rng = np.random.RandomState(3)
datos = np.concatenate([rng.normal(0, 1, 400), rng.normal(3.5, 0.6, 200)])
fig, ax = plt.subplots(figsize=(5.2, 3.6))
ax.hist(datos, bins=30, density=True, alpha=0.6, color="#1f77b4", edgecolor="white")
try:
from scipy.stats import gaussian_kde
kde = gaussian_kde(datos)
xs = np.linspace(datos.min(), datos.max(), 200)
ax.plot(xs, kde(xs), color="#d62728", lw=2.4, label="KDE")
ax.legend(fontsize=10)
except Exception:
pass
ax.set_title("Histograma + KDE", fontsize=12, fontweight="bold")
ax.set_xlabel("Valor", fontsize=11)
ax.set_ylabel("Densidad", fontsize=11)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_boxplot():
rng = np.random.RandomState(5)
datos = np.concatenate([rng.normal(10, 2, 200), [20, 22, 24, -3]])
fig, ax = plt.subplots(figsize=(5.0, 3.2))
ax.boxplot(datos, vert=False, patch_artist=True,
boxprops=dict(facecolor="#cfe2f3"))
q1, med, q3 = np.percentile(datos, [25, 50, 75])
ax.set_title(f"Boxplot (Q1={q1:.1f}, med={med:.1f}, Q3={q3:.1f})",
fontsize=11, fontweight="bold")
ax.set_xlabel("Valor", fontsize=11)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_correlation_heatmap():
rng = np.random.RandomState(0)
X = rng.randn(200, 5)
X[:, 1] = X[:, 0] + rng.randn(200) * 0.4
X[:, 4] = -X[:, 3] + rng.randn(200) * 0.5
corr = np.corrcoef(X.T)
fig, ax = plt.subplots(figsize=(4.8, 4.0))
im = ax.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1)
labels = [f"x{i+1}" for i in range(5)]
ax.set_xticks(range(5))
ax.set_yticks(range(5))
ax.set_xticklabels(labels, fontsize=10)
ax.set_yticklabels(labels, fontsize=10)
for i in range(5):
for j in range(5):
ax.text(j, i, f"{corr[i, j]:.2f}", ha="center", va="center",
color="white" if abs(corr[i, j]) > 0.5 else "black",
fontsize=9)
ax.set_title("Matriz de correlacion", fontsize=12, fontweight="bold")
fig.colorbar(im, ax=ax, fraction=0.045)
fig.tight_layout()
return fig
def _figura_lasso_ridge_geom():
fig, axes = plt.subplots(1, 2, figsize=(7.4, 3.6))
theta = np.linspace(0, 2 * np.pi, 100)
ax = axes[0]
rombo_x = [1, 0, -1, 0, 1]
rombo_y = [0, 1, 0, -1, 0]
ax.fill(rombo_x, rombo_y, color="#ffe0e0", ec="#d62728", lw=2,
label="Region L1 (Lasso)")
for r in [0.4, 0.7, 1.0, 1.3]:
ax.plot(1.6 + r * np.cos(theta), 0.6 + r * np.sin(theta),
color="#1f77b4", lw=1, alpha=0.7)
ax.scatter([1.6], [0.6], color="black", marker="x", s=80)
ax.scatter([1.0], [0.0], color="red", s=110, zorder=5, label="optimo (b2=0)")
ax.axhline(0, color="black", lw=0.5)
ax.axvline(0, color="black", lw=0.5)
ax.set_xlim(-1.6, 2.6)
ax.set_ylim(-1.6, 1.6)
ax.set_aspect("equal")
ax.set_title("Lasso: vertices -> sparsity", fontsize=11, fontweight="bold")
ax.legend(fontsize=8)
ax.grid(alpha=0.3)
ax = axes[1]
ax.fill(np.cos(theta), np.sin(theta), color="#e0e8ff", ec="#1f77b4", lw=2,
label="Region L2 (Ridge)")
for r in [0.4, 0.7, 1.0, 1.3]:
ax.plot(1.6 + r * np.cos(theta), 0.6 + r * np.sin(theta),
color="#1f77b4", lw=1, alpha=0.7)
ax.scatter([1.6], [0.6], color="black", marker="x", s=80)
ax.scatter([0.93], [0.36], color="red", s=110, zorder=5, label="optimo (no anula)")
ax.axhline(0, color="black", lw=0.5)
ax.axvline(0, color="black", lw=0.5)
ax.set_xlim(-1.6, 2.6)
ax.set_ylim(-1.6, 1.6)
ax.set_aspect("equal")
ax.set_title("Ridge: interior -> sin sparsity", fontsize=11, fontweight="bold")
ax.legend(fontsize=8)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_ts_components():
t = np.arange(0, 120)
trend = 0.06 * t
seasonality = 2 * np.sin(2 * np.pi * t / 12)
noise = np.random.RandomState(2).randn(len(t)) * 0.5
serie = trend + seasonality + noise
fig, axes = plt.subplots(4, 1, figsize=(5.6, 5.2), sharex=True)
axes[0].plot(t, serie, color="#1f77b4")
axes[0].set_title("Serie observada", fontsize=10, fontweight="bold")
axes[1].plot(t, trend, color="#2ca02c")
axes[1].set_title("Tendencia", fontsize=10, fontweight="bold")
axes[2].plot(t, seasonality, color="#ff7f0e")
axes[2].set_title("Estacionalidad", fontsize=10, fontweight="bold")
axes[3].plot(t, noise, color="#d62728")
axes[3].set_title("Residuo", fontsize=10, fontweight="bold")
axes[3].set_xlabel("Tiempo (meses)")
for ax in axes:
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_sliding_window():
fig, ax = plt.subplots(figsize=(5.8, 3.6))
ax.set_xlim(0, 12)
ax.set_ylim(0, 6)
ax.axis("off")
serie_y = 4.6
for t in range(10):
ax.add_patch(plt.Rectangle((0.6 + t * 1.1, serie_y), 0.95, 0.6,
fc="#cfe2f3", ec="black"))
ax.text(1.075 + t * 1.1, serie_y + 0.3, f"y{t+1}",
ha="center", va="center", fontsize=9)
ax.text(0.3, serie_y + 0.3, "Serie:", ha="right", fontsize=10, fontweight="bold")
win_start = 0.6
win_w = 0.95 * 4 + 0.6 * 3 + 0.5
ax.add_patch(plt.Rectangle((win_start - 0.1, serie_y - 0.15), win_w, 0.9,
fc="none", ec="red", lw=2, ls="--"))
ax.annotate("ventana (k=4)", xy=(2.2, serie_y + 1.0), fontsize=10, color="red")
ax.annotate("target", xy=(0.6 + 4 * 1.1 + 0.475, serie_y - 0.4),
xytext=(0.6 + 4 * 1.1 + 0.475, 3.0),
arrowprops=dict(arrowstyle="->", color="green"),
ha="center", fontsize=10, color="green")
ax.text(0.3, 1.5, "X:", ha="right", fontsize=10, fontweight="bold")
ax.text(0.3, 0.7, "y:", ha="right", fontsize=10, fontweight="bold")
ax.text(0.6, 1.5, "[y1, y2, y3, y4]", fontsize=10)
ax.text(0.6, 0.7, "y5", fontsize=10)
ax.text(5.0, 1.5, "[y2, y3, y4, y5]", fontsize=10)
ax.text(5.0, 0.7, "y6", fontsize=10)
ax.text(9.4, 1.5, "...", fontsize=10)
ax.set_title("Sliding window (k=4)", fontsize=12, fontweight="bold")
fig.tight_layout()
return fig
def _figura_backtesting():
fig, ax = plt.subplots(figsize=(6.2, 3.6))
ax.set_xlim(0, 24)
ax.set_ylim(-0.5, 4.5)
ax.axis("off")
ax.set_title("Backtesting walk-forward", fontsize=12, fontweight="bold")
for it, train_end in enumerate([8, 11, 14, 17]):
y = 3.5 - it
ax.add_patch(plt.Rectangle((1, y - 0.3), train_end - 1, 0.6,
fc="#cfe2f3", ec="black"))
ax.text((1 + train_end - 1) / 2 + 0.5, y, "Train",
ha="center", va="center", fontsize=9)
ax.add_patch(plt.Rectangle((train_end, y - 0.3), 3, 0.6,
fc="#f9cb9c", ec="black"))
ax.text(train_end + 1.5, y, "Test", ha="center", va="center", fontsize=9)
ax.text(0.1, y, f"It {it+1}", fontsize=9, va="center")
fig.tight_layout()
return fig
def _figura_transformer():
fig, ax = plt.subplots(figsize=(6.0, 4.0))
ax.set_xlim(0, 10)
ax.set_ylim(0, 6.5)
ax.axis("off")
cajas = [(1.5, 5.4, "Inputs"),
(1.5, 4.2, "Embedding + Positional"),
(1.5, 2.6, "Self-Attention\n(multi-head)"),
(1.5, 1.2, "Feed-Forward")]
for x, y, t in cajas:
ax.add_patch(plt.Rectangle((x, y - 0.4), 5, 0.8, fc="#cfe2f3", ec="black"))
ax.text(x + 2.5, y, t, ha="center", va="center", fontsize=10)
for y1, y2 in [(5.4, 4.2), (4.2, 2.6), (2.6, 1.2)]:
ax.annotate("", xy=(4.0, y2 + 0.4), xytext=(4.0, y1 - 0.4),
arrowprops=dict(arrowstyle="->", color="grey"))
ax.add_patch(plt.Rectangle((1.5, 0.0), 5, 0.6, fc="#b6d7a8", ec="black"))
ax.text(4.0, 0.3, "Output / cuantiles", ha="center", fontsize=10)
ax.annotate("", xy=(4.0, 0.6), xytext=(4.0, 0.8),
arrowprops=dict(arrowstyle="->", color="grey"))
ax.set_title("Transformer (esquema)", fontsize=12, fontweight="bold")
fig.tight_layout()
return fig
def _figura_calibration():
bins = np.linspace(0, 1, 11)
perfect = bins
over = bins ** 0.7
under = bins ** 1.6
fig, ax = plt.subplots(figsize=(5.0, 4.0))
ax.plot(bins, perfect, "--", color="grey", lw=2, label="Perfectamente calibrado")
ax.plot(bins, over, "o-", color="#d62728", lw=2, label="Sobreconfiado")
ax.plot(bins, under, "s-", color="#1f77b4", lw=2, label="Infraconfiado")
ax.set_xlabel("Probabilidad predicha", fontsize=11)
ax.set_ylabel("Frecuencia observada", fontsize=11)
ax.set_title("Curva de calibracion (reliability)", fontsize=12, fontweight="bold")
ax.legend(fontsize=9)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_cost_curve():
thresholds = np.linspace(0.01, 0.99, 50)
fn_cost, fp_cost = 20, 2
fn = 100 * thresholds
fp = 100 * (1 - thresholds)
total = fn * fn_cost + fp * fp_cost
fig, ax = plt.subplots(figsize=(5.4, 3.6))
ax.plot(thresholds, total, color="#1f77b4", lw=2.4, label="Coste total")
ax.plot(thresholds, fn * fn_cost, "--", color="#d62728", lw=1.6,
label=f"Coste FN ({fn_cost}โฌ/FN)")
ax.plot(thresholds, fp * fp_cost, "--", color="#2ca02c", lw=1.6,
label=f"Coste FP ({fp_cost}โฌ/FP)")
optimo = thresholds[int(np.argmin(total))]
ax.axvline(optimo, color="black", ls=":", lw=2, label=f"Optimo t={optimo:.2f}")
ax.set_xlabel("Umbral de decision", fontsize=11)
ax.set_ylabel("Coste total (โฌ)", fontsize=11)
ax.set_title("Optimizacion del umbral por coste", fontsize=12, fontweight="bold")
ax.legend(fontsize=8)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_drift_perf():
months = np.arange(1, 13)
auc = 0.85 * np.ones_like(months, dtype=float)
auc[5:] -= 0.025 * (months[5:] - 5)
fig, ax = plt.subplots(figsize=(5.4, 3.6))
ax.plot(months, auc, "o-", color="#1f77b4", lw=2.4, markersize=8)
ax.axhline(0.75, ls="--", color="red", lw=1.6, label="SLA (AUC=0.75)")
ax.axvline(6, ls=":", color="grey", lw=1.5, label="Cambio externo")
ax.set_xlabel("Mes en produccion", fontsize=11)
ax.set_ylabel("AUC", fontsize=11)
ax.set_title("Drift del modelo en produccion", fontsize=12, fontweight="bold")
ax.legend(fontsize=9)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_feature_importance():
features = ["Income", "Age", "Score", "Debt", "Loans", "Education"]
imp = [0.32, 0.25, 0.18, 0.14, 0.08, 0.03]
fig, ax = plt.subplots(figsize=(5.0, 3.2))
ax.barh(features[::-1], imp[::-1], color="#1f77b4", alpha=0.8)
ax.set_xlabel("Importancia (MDI)", fontsize=11)
ax.set_title("Feature importance (Random Forest)", fontsize=12, fontweight="bold")
ax.grid(alpha=0.3, axis="x")
fig.tight_layout()
return fig
def _figura_stratified():
fig, axes = plt.subplots(2, 1, figsize=(6.0, 3.6))
rng = np.random.RandomState(0)
data = np.array([1] * 95 + [0] * 5)
rng.shuffle(data)
folds = np.array_split(np.arange(100), 5)
for i, fold in enumerate(folds):
cols = ["#1f77b4" if data[j] == 1 else "#d62728" for j in fold]
axes[0].scatter(fold, [i] * len(fold), c=cols, s=14)
axes[0].set_title("KFold aleatorio (fold 0 sin minoritaria!)", fontsize=10, fontweight="bold")
axes[0].set_yticks(range(5))
axes[0].set_yticklabels([f"Fold {i+1}" for i in range(5)])
sorted_idx = np.argsort(-data)
for i in range(5):
fold_idx = sorted_idx[i::5]
cols = ["#1f77b4" if data[j] == 1 else "#d62728" for j in fold_idx]
axes[1].scatter(fold_idx, [i] * len(fold_idx), c=cols, s=14)
axes[1].set_title("StratifiedKFold (proporciones preservadas)", fontsize=10, fontweight="bold")
axes[1].set_yticks(range(5))
axes[1].set_yticklabels([f"Fold {i+1}" for i in range(5)])
fig.tight_layout()
return fig
def _figura_loss_explode():
epochs = np.arange(1, 21)
train = 1.5 * np.exp(-epochs / 3) + 0.2
train[7:] = np.nan
val = train + 0.1
fig, ax = plt.subplots(figsize=(5.2, 3.6))
ax.plot(epochs, train, "o-", label="Train loss", color="#1f77b4", lw=2)
ax.plot(epochs, val, "s-", label="Val loss", color="#ff7f0e", lw=2)
ax.text(8.5, 0.6, "NaN!", fontsize=22, color="red", fontweight="bold")
ax.axvline(8, ls="--", color="red", lw=1.5)
ax.set_xlabel("Epoch", fontsize=11)
ax.set_ylabel("Loss", fontsize=11)
ax.set_title("Loss explota (gradient explosion)", fontsize=12, fontweight="bold")
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_auc_overlap():
fig, ax = plt.subplots(figsize=(4.8, 3.8))
fpr = np.linspace(0, 1, 200)
tprA = fpr ** 0.28
tprB = fpr ** 0.26
ax.plot(fpr, tprA, lw=2.4, label="Modelo A (AUC=0.78)", color="#1f77b4")
ax.plot(fpr, tprB, lw=2.4, label="Modelo B (AUC=0.79)", color="#ff7f0e")
ax.plot([0, 1], [0, 1], "--", color="grey")
ax.set_xlabel("FPR", fontsize=11)
ax.set_ylabel("TPR", fontsize=11)
ax.set_title("A/B testing de modelos", fontsize=12, fontweight="bold")
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_ts_regime():
t = np.arange(120)
serie = 0.1 * t + 2 * np.sin(2 * np.pi * t / 12)
serie[60:] -= 8
serie += np.random.RandomState(0).randn(120) * 0.5
fig, ax = plt.subplots(figsize=(5.6, 3.4))
ax.plot(t, serie, color="#1f77b4", lw=1.6)
ax.axvline(60, ls="--", color="red", lw=2, label="Cambio de regimen")
ax.set_xlabel("Tiempo (meses)", fontsize=11)
ax.set_title("Cambio de regimen estructural", fontsize=12, fontweight="bold")
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_scaling_demo():
fig, axes = plt.subplots(1, 2, figsize=(7.8, 3.6))
rng = np.random.RandomState(0)
age = rng.uniform(20, 70, 60)
income = rng.uniform(15000, 100000, 60)
classes = (income > 50000).astype(int)
colors = ["#1f77b4" if c else "#d62728" for c in classes]
axes[0].scatter(age, income, c=colors, alpha=0.75, s=40)
axes[0].set_xlabel("Edad", fontsize=10)
axes[0].set_ylabel("Ingresos (โฌ)", fontsize=10)
axes[0].set_title("Sin escalar (ingresos dominan)", fontsize=10, fontweight="bold")
axes[0].grid(alpha=0.3)
age_s = (age - age.mean()) / age.std()
inc_s = (income - income.mean()) / income.std()
axes[1].scatter(age_s, inc_s, c=colors, alpha=0.75, s=40)
axes[1].set_xlabel("Edad (z-score)", fontsize=10)
axes[1].set_ylabel("Ingresos (z-score)", fontsize=10)
axes[1].set_title("Tras StandardScaler", fontsize=10, fontweight="bold")
axes[1].grid(alpha=0.3)
fig.tight_layout()
return fig
def render_grafico(spec: dict):
if spec is None:
return None
tipo = spec.get("tipo")
mapping = {
"roc": lambda: _figura_roc(spec.get("auc", 0.9)),
"loss": lambda: _figura_loss(spec.get("modo", "good")),
"learning_curve": lambda: _figura_learning_curve(spec.get("modo", "data_helps")),
"densities": lambda: _figura_densidades(spec.get("separacion", "media")),
"kmeans": _figura_kmeans,
"elbow": _figura_elbow,
"scree": _figura_scree,
"acf": _figura_acf,
"confusion": lambda: _figura_confusion(spec.get("tp", 80), spec.get("fn", 10),
spec.get("fp", 20), spec.get("tn", 900)),
"perceptron": _figura_perceptron,
"neural_network": _figura_red_neuronal,
"activations": _figura_activaciones,
"sigmoid_logistic": _figura_sigmoid_logistic,
"bias_variance": _figura_bias_variance,
"decision_tree": _figura_decision_tree,
"bagging_vs_boosting": _figura_bagging_vs_boosting,
"histogram_kde": _figura_histogram_kde,
"boxplot": _figura_boxplot,
"correlation_heatmap": _figura_correlation_heatmap,
"lasso_ridge_geom": _figura_lasso_ridge_geom,
"ts_components": _figura_ts_components,
"sliding_window": _figura_sliding_window,
"backtesting": _figura_backtesting,
"transformer": _figura_transformer,
"calibration": _figura_calibration,
"cost_curve": _figura_cost_curve,
"drift_perf": _figura_drift_perf,
"feature_importance": _figura_feature_importance,
"stratified_demo": _figura_stratified,
"loss_explode": _figura_loss_explode,
"auc_overlap": _figura_auc_overlap,
"ts_regime": _figura_ts_regime,
"scaling_demo": _figura_scaling_demo,
}
func = mapping.get(tipo)
return func() if func else None
# -----------------------------------------------------------------------------
# Estilos CSS
# -----------------------------------------------------------------------------
CSS = """
<style>
/* fuente base mas grande */
html, body, [class*="css"] {
font-size: 18px !important;
}
.stMarkdown p, .stMarkdown li {
font-size: 1.05rem;
line-height: 1.55;
}
/* boton primario en azul UAX */
.stButton button {
font-size: 1.05rem !important;
padding: 0.55rem 1.1rem;
border-radius: 8px;
font-weight: 500;
}
/* Tarjeta de pregunta */
.pregunta-card {
background: linear-gradient(135deg, #f8f9fb 0%, #e9eff7 100%);
border-left: 5px solid #1f77b4;
padding: 1.2rem 1.4rem;
border-radius: 10px;
margin: 0.8rem 0 1rem 0;
box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}
.pregunta-card h3 {
margin-top: 0;
color: #1f3a68;
font-size: 1.05rem;
}
.pregunta-card .enunciado {
font-size: 1.18rem;
line-height: 1.55;
color: #1c1c1c;
margin-top: 0.6rem;
}
.bloque-badge {
display: inline-block;
background-color: #1f77b4;
color: white;
padding: 0.25rem 0.7rem;
border-radius: 999px;
font-size: 0.9rem;
font-weight: 500;
}
.hero-title {
font-size: 2.6rem;
font-weight: 700;
color: #1f3a68;
margin-bottom: 0.2rem;
}
.hero-subtitle {
font-size: 1.2rem;
color: #555;
margin-top: 0;
}
.info-pill {
display: inline-block;
background-color: #eef4fb;
color: #1f3a68;
padding: 0.4rem 0.9rem;
border-radius: 999px;
margin: 0.2rem 0.3rem;
font-size: 1rem;
font-weight: 500;
}
/* Radio buttons mas legibles */
div[data-baseweb="radio"] label {
font-size: 1.08rem !important;
padding: 0.3rem 0;
}
/* Reveal box */
.reveal-box {
background: #f1f8ff;
border: 1px solid #c6dafa;
padding: 1rem 1.2rem;
border-radius: 10px;
margin-top: 0.8rem;
}
.slide-ref {
font-size: 0.95rem;
color: #555;
font-style: italic;
}
</style>
"""
# -----------------------------------------------------------------------------
# Estado y logica del examen
# -----------------------------------------------------------------------------
def _resetear_examen(modo: str, preguntas: list[dict], bloques: list[str] | None = None):
pool = preguntas
if bloques:
pool = [q for q in preguntas if q["bloque"] in bloques]
if not pool:
pool = preguntas
if modo == "rapido":
seleccion = random.sample(pool, min(20, len(pool)))
elif modo == "medio":
seleccion = random.sample(pool, min(50, len(pool)))
elif modo == "bloque":
seleccion = list(pool)
else:
seleccion = list(preguntas)
st.session_state.examen = seleccion
st.session_state.modo = modo
st.session_state.indice = 0
st.session_state.respuestas = {}
st.session_state.revelado = {}
st.session_state.finalizado = False
st.session_state.bloques_filtro = bloques or []
def _pantalla_inicio(preguntas: list[dict]):
# Header visual
col_logo, col_title = st.columns([1, 5])
with col_logo:
st.markdown("<div style='font-size:4.5rem; text-align:center;'>๐</div>",
unsafe_allow_html=True)
with col_title:
st.markdown(
"<div class='hero-title'>Banco de Examen IA</div>"
"<p class='hero-subtitle'>Grado en Ingenieria Matematica ยท UAX</p>",
unsafe_allow_html=True,
)
st.markdown("---")
# Stats pills
bloques: dict[str, int] = {}
con_grafico = 0
for q in preguntas:
bloques[q["bloque"]] = bloques.get(q["bloque"], 0) + 1
if q.get("grafico"):
con_grafico += 1
pills = (
f"<span class='info-pill'>๐ {len(preguntas)} preguntas</span>"
f"<span class='info-pill'>๐ {con_grafico} con grafico/esquema</span>"
f"<span class='info-pill'>๐๏ธ {len(bloques)} bloques</span>"
)
st.markdown(pills, unsafe_allow_html=True)
st.markdown("### ๐ Distribucion por bloque")
cols = st.columns(2)
bloques_ordenados = sorted(bloques.items(),
key=lambda kv: int(kv[0].split(".")[0]))
for i, (b, n) in enumerate(bloques_ordenados):
icon = BLOQUE_ICONOS.get(b, "๐")
nombre = b.split(". ", 1)[1] if ". " in b else b
with cols[i % 2]:
st.markdown(f"{icon} **{nombre}** โ _{n} preguntas_")
st.markdown("---")
st.markdown("### ๐ฏ Elige modo de practica")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("โก Examen rapido\n(20 preguntas)", use_container_width=True, type="primary"):
_resetear_examen("rapido", preguntas)
st.rerun()
with col2:
if st.button("๐ Examen medio\n(50 preguntas)", use_container_width=True, type="primary"):
_resetear_examen("medio", preguntas)
st.rerun()
with col3:
if st.button(f"๐ Modo estudio\n({len(preguntas)} preguntas)", use_container_width=True):
_resetear_examen("completo", preguntas)
st.rerun()
st.markdown("---")
st.markdown("### ๐๏ธ O practica por bloque tematico")
opciones = [f"{BLOQUE_ICONOS.get(b, '๐')} {b}"
for b, _ in bloques_ordenados]
raw_map = {f"{BLOQUE_ICONOS.get(b, '๐')} {b}": b for b, _ in bloques_ordenados}
sel = st.multiselect(
"Selecciona uno o varios bloques (deja vacio para usar todos):",
opciones,
default=[],
)
cantidad = st.radio(
"Cuantas preguntas quieres del/los bloque/s elegido/s?",
options=["Todas", "20 aleatorias", "50 aleatorias"],
index=0,
horizontal=True,
)
if st.button("๐ Empezar por bloque", use_container_width=True, type="primary"):
bloques_sel = [raw_map[s] for s in sel] if sel else None
if cantidad == "Todas":
_resetear_examen("bloque", preguntas, bloques_sel)
elif cantidad == "20 aleatorias":
_resetear_examen("rapido", preguntas, bloques_sel)
else:
_resetear_examen("medio", preguntas, bloques_sel)
st.rerun()
def _pantalla_resultados():
examen = st.session_state.examen
respuestas = st.session_state.respuestas
total = len(examen)
aciertos = sum(
1 for i, q in enumerate(examen)
if respuestas.get(i) == q["respuesta"]
)
nota = 10.0 * aciertos / total if total else 0.0
st.markdown("## ๐ Resultado del examen")
col1, col2, col3 = st.columns(3)
col1.metric("๐ Preguntas", total)
col2.metric("โ
Aciertos", aciertos)
col3.metric("๐ฏ Nota", f"{nota:.2f} / 10")
if nota >= 7:
st.success("๐ Excelente! Sigue asi.")
elif nota >= 5:
st.info("๐ Aprobado. Revisa los fallos a continuacion.")
else:
st.warning("๐ Suspenso: repasa el temario y vuelve a intentarlo.")
with st.expander("๐ Revisar todas las preguntas y soluciones", expanded=False):
for i, q in enumerate(examen):
user_ans = respuestas.get(i)
correcta = q["respuesta"]
ok = user_ans == correcta
estado = "โ
" if ok else "โ"
icon = BLOQUE_ICONOS.get(q["bloque"], "๐")
st.markdown(f"### {estado} Pregunta {i+1} ยท {icon} _{q['bloque']}_")
st.markdown(f"**{q['enunciado']}**")
if q.get("grafico"):
fig = render_grafico(q["grafico"])
if fig is not None:
st.pyplot(fig)
plt.close(fig)
for j, opt in enumerate(q["opciones"]):
prefijo = "โ
" if j == correcta else "โซ๏ธ"
marca = ""
if user_ans == j and j != correcta:
marca = " โฌ
๏ธ tu respuesta"
st.markdown(f"- {prefijo} **{chr(65+j)}.** {opt}{marca}")
st.markdown(f"๐ก **Explicacion:** {q['explicacion']}")
st.caption(f"๐ Referencia: {q['slide_ref']}")
st.markdown("---")
if st.button("๐ Volver al inicio"):
for k in ["examen", "modo", "indice", "respuestas", "revelado", "finalizado", "bloques_filtro"]:
st.session_state.pop(k, None)
st.rerun()
def _pantalla_pregunta():
examen = st.session_state.examen
idx = st.session_state.indice
total = len(examen)
q = examen[idx]
icon = BLOQUE_ICONOS.get(q["bloque"], "๐")
# Barra de progreso visual
st.progress((idx + 1) / total)
st.caption(
f"๐ Pregunta **{idx+1}** de **{total}** ยท "
f"Modo: _{st.session_state.modo}_ ยท "
f"Contestadas: **{len(st.session_state.respuestas)}/{total}**"
)
# Cabecera con badge de bloque (HTML para el badge, markdown nativo para el enunciado)
st.markdown(
f"<span class='bloque-badge'>{icon} {q['bloque']}</span>",
unsafe_allow_html=True,
)
# El enunciado va con markdown puro para que el LaTeX ($...$) se renderice
st.markdown(f"### {q['enunciado']}")
# Grafico
if q.get("grafico"):
fig = render_grafico(q["grafico"])
if fig is not None:
st.pyplot(fig)
plt.close(fig)
# Opciones
opciones_etiquetadas = [f"{chr(65+i)}. {o}" for i, o in enumerate(q["opciones"])]
actual = st.session_state.respuestas.get(idx)
seleccion = st.radio(
"**Selecciona tu respuesta:**",
options=list(range(len(q["opciones"]))),
format_func=lambda i: opciones_etiquetadas[i],
index=actual if actual is not None else None,
key=f"radio_{idx}",
)
if seleccion is not None:
st.session_state.respuestas[idx] = seleccion
# Botones
revelado = st.session_state.revelado.get(idx, False)
col_a, col_b, col_c, col_d = st.columns([1.3, 1, 1, 1.3])
with col_a:
if st.button("๐ก Mostrar respuesta", key=f"reveal_{idx}", use_container_width=True):
st.session_state.revelado[idx] = True
revelado = True
with col_b:
if st.button("โ๏ธ Anterior", disabled=idx == 0, key=f"prev_{idx}", use_container_width=True):
st.session_state.indice = max(0, idx - 1)
st.rerun()
with col_c:
if st.button(
"Siguiente โถ๏ธ",
disabled=idx >= total - 1,
key=f"next_{idx}",
use_container_width=True,
):
st.session_state.indice = min(total - 1, idx + 1)
st.rerun()
with col_d:
if st.button("๐ Finalizar y corregir", key=f"end_{idx}",
use_container_width=True, type="primary"):
st.session_state.finalizado = True
st.rerun()
if revelado:
correcta = q["respuesta"]
marca = chr(65 + correcta)
if st.session_state.respuestas.get(idx) == correcta:
st.success(f"โ
**Correcto.** Opcion **{marca}**.")
elif idx in st.session_state.respuestas:
st.error(f"โ **Incorrecto.** La opcion correcta es la **{marca}**.")
else:
st.info(f"โน๏ธ La opcion correcta es la **{marca}**.")
# Justificacion en markdown puro para que el LaTeX renderice
with st.container():
st.markdown(f"**๐ก Justificacion:**")
st.markdown(q["explicacion"])
st.caption(f"๐ Referencia en PowerPoint: {q['slide_ref']}")
def main():
st.set_page_config(
page_title="Banco de Examen IA ยท UAX",
page_icon="๐",
layout="centered",
initial_sidebar_state="expanded",
)
st.markdown(CSS, unsafe_allow_html=True)
preguntas = cargar_preguntas()
with st.sidebar:
st.markdown("<div style='font-size:3rem; text-align:center;'>๐</div>",
unsafe_allow_html=True)
st.markdown("### Banco de Examen IA")
st.markdown("**UAX ยท Ing. Matematica**")
st.markdown("---")
st.markdown(f"๐ **Total:** {len(preguntas)} preguntas")
con_grafico = sum(1 for q in preguntas if q.get("grafico"))
st.markdown(f"๐ **Con grafico:** {con_grafico}")
if "examen" in st.session_state:
st.markdown("---")
st.markdown(f"๐ฏ **Modo:** _{st.session_state.modo}_")
st.markdown(
f"๐ **Pregunta:** {st.session_state.indice+1} / {len(st.session_state.examen)}"
)
st.markdown(f"โ
**Contestadas:** {len(st.session_state.respuestas)}")
if st.button("๐ Reiniciar / cambiar modo", use_container_width=True):
for k in ["examen", "modo", "indice", "respuestas",
"revelado", "finalizado", "bloques_filtro"]:
st.session_state.pop(k, None)
st.rerun()
st.markdown("---")
st.caption("Streamlit ยท matplotlib ยท 30+ tipos de grafico dinamico.")
if "examen" not in st.session_state:
_pantalla_inicio(preguntas)
elif st.session_state.get("finalizado"):
_pantalla_resultados()
else:
_pantalla_pregunta()
if __name__ == "__main__":
main()
# -*- coding: utf-8 -*-
"""Banco de Examen IA - Streamlit App (UAX, Ingenieria Matematica).
Modos:
- Examen rapido: 20 preguntas aleatorias.
- Examen medio: 50 preguntas aleatorias.
- Modo estudio: las 225 preguntas en orden.
- Por bloque: selecciona uno o varios bloques tematicos.
Cada pregunta puede llevar un grafico dinamico (matplotlib). El alumno
selecciona la opcion y pulsa "Mostrar respuesta" para ver la solucion,
la justificacion y la referencia exacta a la slide del PowerPoint.
"""
from __future__ import annotations
import json
import random
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import streamlit as st
# -----------------------------------------------------------------------------
# Iconos por bloque (emoji + color)
# -----------------------------------------------------------------------------
BLOQUE_ICONOS = {
"0. Conceptos basicos para empezar": "๐ฑ",
"1. Introduccion a la IA, historia y etica": "๐ค",
"2. Tipos de ML/DL y arquitectura de solucion": "๐ง ",
"3. EDA - Analisis Exploratorio de Datos": "๐",
"4. Evaluacion de modelos de clasificacion": "๐ฏ",
"5. Modelos de Clasificacion I": "๐ณ",
"6. Overfitting, Underfitting y Balanceo": "โ๏ธ",
"7. Evaluacion de modelos de regresion": "๐",
"8. Regresion lineal, no lineal y arboles": "๐",
"9. Ridge, Lasso y Regresion Logistica": "๐๏ธ",
"10. Redes Neuronales": "๐ฎ",
"11. Series Temporales": "โฑ๏ธ",
"13. Casos practicos avanzados de modelos y evaluacion": "๐",
}
# -----------------------------------------------------------------------------
# Carga de datos
# -----------------------------------------------------------------------------
def cargar_preguntas() -> list[dict]:
ruta = Path(__file__).parent / "questions.json"
with ruta.open(encoding="utf-8") as f:
return json.load(f)
# -----------------------------------------------------------------------------
# Renderizado de graficos matplotlib
# -----------------------------------------------------------------------------
def _figura_roc(auc_objetivo: float):
fig, ax = plt.subplots(figsize=(4.8, 4.2))
fpr = np.linspace(0, 1, 200)
if abs(auc_objetivo - 0.5) < 1e-3:
tpr = fpr.copy()
else:
gamma = max(0.001, (1 - auc_objetivo) / max(auc_objetivo, 1e-3))
tpr = fpr ** gamma
ax.plot(fpr, tpr, lw=2.6, color="#1f77b4", label=f"Modelo (AUC~{auc_objetivo:.2f})")
ax.plot([0, 1], [0, 1], "--", color="grey", label="Azar (AUC=0.5)")
ax.set_xlabel("FPR (Falsos Positivos)", fontsize=11)
ax.set_ylabel("TPR (Recall / Sensibilidad)", fontsize=11)
ax.set_title("Curva ROC", fontsize=12, fontweight="bold")
ax.legend(loc="lower right", fontsize=9)
ax.grid(alpha=0.3)
fig.tight_layout()
return fig
def _figura_loss(modo: str):
epochs = np.arange(1, 51)
fig, ax = plt.subplots(figsize=(4.8, 3.8))
if modo == "overfit":
train = 1.2 * np.exp(-epochs / 12) + 0.05
val = 1.2 * np.exp(-epochs / 10) + 0.05 + 0.4 * (1 - np.exp(-(epochs - 18).clip(0) / 12))
titulo = "Overfitting"
elif modo == "underfit":
train = 1.0 - 0.08 * np.tanh(epochs / 30) + 0.02 * np.random.RandomState(0).randn(len(epochs))
val = train + 0.04
titulo = "Underfitting"
else:
train = 0.9 * np.exp(-epochs / 10) + 0.1
val = 0.95 * np.exp(-epochs / 11) + 0.12
titulo = "Buen ajuste"
ax.plot(epochs, train, lw=2.4, label="Train loss", color="#1f77b4")
ax.plot(epochs, val, lw=2.4, label="Val loss", color="#ff7f0e")
ax.set_xlabel("Epoch", fontsize=11)
ax.set_ylabel("Loss", fontsize=11)
ax.set_title(f"Curva de perdida ({titulo})", fontsize=12, fontweight="bold")
ax.legend(fontsize=10)