File size: 47,868 Bytes
5361b8a a643bcf 5361b8a e735979 5361b8a d95438e 5361b8a d95438e 5361b8a d95438e 5361b8a d95438e 5361b8a | 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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 | # -*- 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()
|