Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- appDiplo.py +186 -101
- requirements.txt +0 -0
- style.css +0 -1
- varianza.py +80 -0
appDiplo.py
CHANGED
|
@@ -64,17 +64,11 @@ from sklearn.compose import ColumnTransformer
|
|
| 64 |
# fin prg MAF
|
| 65 |
# endregion IMPORTACIÓN DE LIBRERÍAS
|
| 66 |
|
| 67 |
-
# Habilitar para Hugging Face
|
| 68 |
-
#import spaces
|
| 69 |
-
#@spaces.GPU
|
| 70 |
-
#def _dummy():
|
| 71 |
-
# pass
|
| 72 |
-
# hasta aca ...
|
| 73 |
|
| 74 |
# region CONSTANTES Y DICCIONARIOS
|
| 75 |
# --- Constantes ---
|
| 76 |
-
DATA_PATH = "./
|
| 77 |
-
IMAGE_PATH = "./
|
| 78 |
FILE_MAP = {
|
| 79 |
"ARROZ": "arroz_depurado.csv",
|
| 80 |
"AVENA": "avena_depurado.csv",
|
|
@@ -106,34 +100,12 @@ NO_EXISTE = 999 # Para indicar que no se aplicó la prueba ADF o que no se calcu
|
|
| 106 |
YEAR_MIN = 1930 # Primer año de la serie de datos
|
| 107 |
YEAR_MAX = 2024 # ültimo año de la serie de datos
|
| 108 |
|
| 109 |
-
# Mapeo indicador (nombre corto) -> columna interna y unidad, sin distinguir mayúsculas/minúsculas
|
| 110 |
-
INDICADOR_COL = {
|
| 111 |
-
'sup.semb.[ha]': 'sup_sem_ha',
|
| 112 |
-
'sup.cos.[ha]': 'sup_cos_ha',
|
| 113 |
-
'rend.[kg/ha]': 'rend_kgxha',
|
| 114 |
-
'prod.[ton]': 'prod_ton',
|
| 115 |
-
}
|
| 116 |
-
INDICADOR_UNIDAD = {
|
| 117 |
-
'sup.semb.[ha]': ' ha',
|
| 118 |
-
'sup.cos.[ha]': ' ha',
|
| 119 |
-
'rend.[kg/ha]': ' kg/ha',
|
| 120 |
-
'prod.[ton]': ' ton',
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
def indicador_a_col(nombre):
|
| 124 |
-
"""Convierte el nombre corto del indicador (cualquier capitalización) a la columna interna."""
|
| 125 |
-
return INDICADOR_COL.get(str(nombre).strip().lower(), nombre)
|
| 126 |
-
|
| 127 |
-
def indicador_a_unidad(nombre):
|
| 128 |
-
"""Devuelve la unidad del indicador (cualquier capitalización)."""
|
| 129 |
-
return INDICADOR_UNIDAD.get(str(nombre).strip().lower(), "")
|
| 130 |
-
|
| 131 |
# Se cargan las descripciones de las variables de los datasets en un diccionario
|
| 132 |
# para títulos de gráficos de evolución de cultivos
|
| 133 |
-
variables = os.path.join(DATA_PATH, "
|
| 134 |
df_vars = pd.read_csv(variables, header=None, encoding='latin-1', sep=',')
|
| 135 |
dict_nlargos = df_vars.set_index(df_vars.columns[0])[df_vars.columns[1]].to_dict()
|
| 136 |
-
variables = os.path.join(DATA_PATH, "
|
| 137 |
df_vars = pd.read_csv(variables, header=None, encoding='latin-1', sep=',')
|
| 138 |
dict_ncortos = df_vars.set_index(df_vars.columns[0])[df_vars.columns[1]].to_dict()
|
| 139 |
# endregion CONSTANTES Y DICCIONARIOS
|
|
@@ -3418,7 +3390,7 @@ def tab_ST_diff_ADF(df, indicador, grado, graficar=True, diferenciar=True, aplic
|
|
| 3418 |
</div>
|
| 3419 |
"""
|
| 3420 |
elif n_obs > 4: # Mínimo de observaciones para una prueba con lags
|
| 3421 |
-
res = adfuller(serie_test, autolag='AIC')
|
| 3422 |
test_stat, p_value, lags_used, crit_values = res[0], res[1], res[2], res[4]
|
| 3423 |
|
| 3424 |
es_estacionaria = p_value < 0.05
|
|
@@ -3616,10 +3588,9 @@ def tab_ST_ARIMA(df, indicador, p, d, q, n, graf=False):
|
|
| 3616 |
</div>
|
| 3617 |
"""
|
| 3618 |
if graf:
|
| 3619 |
-
return None
|
| 3620 |
-
|
| 3621 |
else:
|
| 3622 |
-
return pd.DataFrame(), reporte, None, None, None, None, None
|
| 3623 |
|
| 3624 |
# Se verifica que la serie sea estacionaria (NO_EXISTE = sin prueba ADF, no se verificó estacionariedad)
|
| 3625 |
if d == NO_EXISTE:
|
|
@@ -3631,9 +3602,9 @@ def tab_ST_ARIMA(df, indicador, p, d, q, n, graf=False):
|
|
| 3631 |
la prueba ADF para verificar ESTACIONARIEDAD.</div>
|
| 3632 |
"""
|
| 3633 |
if graf:
|
| 3634 |
-
return None
|
| 3635 |
else:
|
| 3636 |
-
return pd.DataFrame(), reporte, None, None, None, None, None
|
| 3637 |
|
| 3638 |
# Se verifica que el dataframe con la serie diferenciada ya exista
|
| 3639 |
if p == NO_EXISTE or q == NO_EXISTE:
|
|
@@ -3647,13 +3618,19 @@ def tab_ST_ARIMA(df, indicador, p, d, q, n, graf=False):
|
|
| 3647 |
if graf:
|
| 3648 |
return None
|
| 3649 |
else:
|
| 3650 |
-
return pd.DataFrame(), reporte, None, None, None, None, None
|
| 3651 |
|
| 3652 |
# Se convierte el nombre corto del "indicador" a su nombre original
|
| 3653 |
ind_orig = next((k for k, v in dict_ncortos.items() if v == indicador), indicador)
|
| 3654 |
|
| 3655 |
# Se aguarda la unidad del indicador
|
| 3656 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3657 |
|
| 3658 |
# Se convierte 'periodo' a formato datetime y establecerlo como índice con frecuencia,
|
| 3659 |
# porque así lo requiere el modelo ARIMA
|
|
@@ -3678,7 +3655,7 @@ def tab_ST_ARIMA(df, indicador, p, d, q, n, graf=False):
|
|
| 3678 |
"<i>p</i> y <i>q</i> calculados.<br>"
|
| 3679 |
f"<i>p</i> = {p}; <i>q</i> = {q}.</div>"
|
| 3680 |
)
|
| 3681 |
-
return pd.DataFrame(), reporte, None, None, None, None, None
|
| 3682 |
|
| 3683 |
|
| 3684 |
|
|
@@ -3848,15 +3825,7 @@ def tab_ST_ARIMA(df, indicador, p, d, q, n, graf=False):
|
|
| 3848 |
'Sup': intervalos.iloc[:, 1].values
|
| 3849 |
})
|
| 3850 |
|
| 3851 |
-
|
| 3852 |
-
# Convertir a lista y rellenar con None o ceros por si faltan elementos, o extraer dinámicamente
|
| 3853 |
-
preds = df_plot_pred['Valor'].round(2).tolist()
|
| 3854 |
-
pred1 = preds[0] if len(preds) > 0 else None
|
| 3855 |
-
pred2 = preds[1] if len(preds) > 1 else None
|
| 3856 |
-
pred3 = preds[2] if len(preds) > 2 else None
|
| 3857 |
-
pred4 = preds[3] if len(preds) > 3 else None
|
| 3858 |
-
pred5 = preds[4] if len(preds) > 4 else None
|
| 3859 |
-
pred6 = preds[5] if len(preds) > 5 else None
|
| 3860 |
|
| 3861 |
# Se agrega al df histórico el primer dato del df predicho para
|
| 3862 |
# que no quede un salto en el gráfico.
|
|
@@ -5340,31 +5309,11 @@ def tab_ST_Fourier_Wavelets_Triple(df_o1, df_o2, df_o3, df_d1, df_d2, df_d3, var
|
|
| 5340 |
|
| 5341 |
# region FUNCIONES PARA IMAGENES/VIDEOS EN BASE64 E INCLUSIÓN EN CÓDIGO CSS
|
| 5342 |
# Función para convertir imagen/video a Base64
|
| 5343 |
-
#def media_to_base64(media_path):
|
| 5344 |
-
# if not os.path.exists(media_path):
|
| 5345 |
-
# return ""
|
| 5346 |
-
# with open(media_path, "rb") as media_file:
|
| 5347 |
-
# return base64.b64encode(media_file.read()).decode('utf-8')
|
| 5348 |
-
def find_file_ci(path):
|
| 5349 |
-
"""Devuelve la ruta real del archivo ignorando mayúsculas/minúsculas (para Linux)."""
|
| 5350 |
-
if os.path.exists(path):
|
| 5351 |
-
return path
|
| 5352 |
-
folder, filename = os.path.split(path)
|
| 5353 |
-
if not os.path.isdir(folder):
|
| 5354 |
-
return None
|
| 5355 |
-
for f in os.listdir(folder):
|
| 5356 |
-
if f.lower() == filename.lower():
|
| 5357 |
-
return os.path.join(folder, f)
|
| 5358 |
-
return None
|
| 5359 |
-
|
| 5360 |
def media_to_base64(media_path):
|
| 5361 |
-
|
| 5362 |
-
if real_path is None:
|
| 5363 |
-
print(f"[ADVERTENCIA] No se encontró: {media_path}")
|
| 5364 |
return ""
|
| 5365 |
-
with open(
|
| 5366 |
-
return base64.b64encode(media_file.read()).decode(
|
| 5367 |
-
|
| 5368 |
|
| 5369 |
# Se lee el contenido del CSS externo para agregar
|
| 5370 |
# las líneas correspondientes a las imágenes de fondo
|
|
@@ -5382,13 +5331,13 @@ img_path_1 = os.path.join(current_dir, "Images", "App_bg.png")
|
|
| 5382 |
img_path_2 = os.path.join(current_dir, "Images", "Title_bg.png")
|
| 5383 |
img_path_3 = os.path.join(current_dir, "Images", "Container_bg.png")
|
| 5384 |
img_path_4 = os.path.join(current_dir, "Images", "header_bg.png")
|
| 5385 |
-
|
| 5386 |
-
vid_path_1 = os.path.join(current_dir, "Images", "
|
| 5387 |
fondo_app = media_to_base64(img_path_1)
|
| 5388 |
fondo_titulo = media_to_base64(img_path_2)
|
| 5389 |
fondo_contenedor = media_to_base64(img_path_3)
|
| 5390 |
fondo_encabezado = media_to_base64(img_path_4)
|
| 5391 |
-
|
| 5392 |
video_portada = media_to_base64(vid_path_1)
|
| 5393 |
|
| 5394 |
# Se agregan al CSS leído, las líneas que aplican las imágenes de fondo en BASE64,
|
|
@@ -5401,6 +5350,7 @@ extra_css = f"""
|
|
| 5401 |
.custom-tab-2 {{ background-image: url('data:image/png;base64,{fondo_contenedor}') !important; }}
|
| 5402 |
.custom-tab-3 {{ background-image: url('data:image/png;base64,{fondo_contenedor}') !important; }}
|
| 5403 |
.header-tab {{ background-image: url('data:image/png;base64,{fondo_encabezado}') !important; }}
|
|
|
|
| 5404 |
.portrait-bg-2 {{ background-image: url('data:image/png;base64,{fondo_titulo}') !important; }}
|
| 5405 |
.modal-ayuda {{ background-image: url('data:image/png;base64,{fondo_contenedor}') !important; }}
|
| 5406 |
.modal-grafico {{ background-image: url('data:image/png;base64,{fondo_contenedor}') !important; }}
|
|
@@ -5636,26 +5586,34 @@ def rf_cargaPredecir(dfData, cultivo_seleccionado, provincia_seleccionada,
|
|
| 5636 |
ultimo_anio_historico = int(periodos_historicos_unicos[-1])
|
| 5637 |
|
| 5638 |
# 3. Mapeo de indicadores y definición de la variable objetivo (target)
|
| 5639 |
-
|
| 5640 |
-
|
| 5641 |
-
|
| 5642 |
-
|
| 5643 |
-
|
| 5644 |
-
|
| 5645 |
-
|
| 5646 |
-
|
| 5647 |
-
|
|
|
|
| 5648 |
|
| 5649 |
-
|
| 5650 |
-
|
|
|
|
|
|
|
|
|
|
| 5651 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5652 |
|
| 5653 |
# Separación de características (X) y variable objetivo (y)
|
| 5654 |
-
|
| 5655 |
-
X = df_trabajo.drop(columns=[target, "periodo", "departamento" , "sup_sem_ha" , "sup_cos_ha" , "prod_ton" ], errors="ignore")
|
| 5656 |
-
print(X)
|
| 5657 |
y = df_trabajo[target]
|
| 5658 |
-
print(y)
|
| 5659 |
|
| 5660 |
# 4. División de datos (Train / Test) y entrenamiento del Random Forest
|
| 5661 |
X_train, X_test, y_train, y_test = train_test_split(
|
|
@@ -5937,8 +5895,21 @@ def tab_NN_train_and_predict_mlp(dataset_type, provincia, departamento, indicado
|
|
| 5937 |
Aplica Codificación Ordinal a fenómenos climáticos y One-Hot Encoding a variables políticas.
|
| 5938 |
"""
|
| 5939 |
# Mapeo de nombres cortos a columnas internas del dataset
|
| 5940 |
-
|
| 5941 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5942 |
|
| 5943 |
# Se filtra el dataset de cultivo
|
| 5944 |
df_cultivo, provincias = load_data(dataset_type)
|
|
@@ -6109,8 +6080,21 @@ def tab_NN_train_and_predict_lstm(dataset_type, provincia, departamento, indicad
|
|
| 6109 |
Mantiene la misma estructura de retorno y formato que la función original MLP.
|
| 6110 |
"""
|
| 6111 |
# Mapeo de nombres cortos a columnas internas del dataset
|
| 6112 |
-
|
| 6113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6114 |
|
| 6115 |
# Se filtra el dataset de cultivo sin incorporar variables externas
|
| 6116 |
df_cultivo, provincias = load_data(dataset_type)
|
|
@@ -6126,8 +6110,7 @@ def tab_NN_train_and_predict_lstm(dataset_type, provincia, departamento, indicad
|
|
| 6126 |
res_df = res_df.sort_values('periodo').reset_index(drop=True)
|
| 6127 |
|
| 6128 |
# Extracción de la serie objetivo
|
| 6129 |
-
serie = res_df[indicador].astype(float).values.reshape(-1, 1)
|
| 6130 |
-
|
| 6131 |
n_obs = len(serie)
|
| 6132 |
|
| 6133 |
# 4. División Hold-Out Cronológica (los últimos 5 años o 3 se reservan para prueba)
|
|
@@ -7007,7 +6990,7 @@ def tab_CM_generar_predicciones(cultivo, provincia, departamento, indicador):
|
|
| 7007 |
# Manejo de fallos o combinaciones vacías
|
| 7008 |
if errores or not combinaciones: # Retorna un DataFrame vacío
|
| 7009 |
return pd.DataFrame(columns=["PROVINCIA", "DEPARTAMENTO",
|
| 7010 |
-
"INIC", "FIN", "AÑOS", "ELIM", "IMP",
|
| 7011 |
"HOLT-WINTERS", "ARIMA", "BOSQUES ALEATORIOS", "RED LSTM"])
|
| 7012 |
|
| 7013 |
# Descartar el elemento 'cultivo' extrayendo únicamente 'provincia' y 'departamento'
|
|
@@ -7017,7 +7000,7 @@ def tab_CM_generar_predicciones(cultivo, provincia, departamento, indicador):
|
|
| 7017 |
df_predicciones = pd.DataFrame(combinaciones_filtradas, columns=["PROVINCIA", "DEPARTAMENTO"])
|
| 7018 |
|
| 7019 |
# Inicializar las columnas de los modelos predictivos con el valor por defecto "---"
|
| 7020 |
-
columnas_data = ["INIC", "FIN", "AÑOS", "ELIM", "IMP",
|
| 7021 |
"HOLT-WINTERS", "ARIMA", "BOSQUES ALEATORIOS", "RED LSTM"]
|
| 7022 |
for col in columnas_data:
|
| 7023 |
df_predicciones[col] = "---"
|
|
@@ -7041,6 +7024,7 @@ def tab_CM_generar_predicciones(cultivo, provincia, departamento, indicador):
|
|
| 7041 |
df_predicciones.at[idx, "AÑOS"] = str(serie)
|
| 7042 |
df_predicciones.at[idx, "ELIM"] = str(elim)
|
| 7043 |
df_predicciones.at[idx, "IMP"] = str(imp)
|
|
|
|
| 7044 |
|
| 7045 |
# Se extraen los últimos 3 valores de la serie histórica
|
| 7046 |
ultimos_historicos: List[float] = df_preparado.iloc[-3:, 1].astype(float).tolist()
|
|
@@ -7249,7 +7233,7 @@ def tab_CM_arima(df: pd.DataFrame, pasos: int) -> list[int]:
|
|
| 7249 |
|
| 7250 |
return predicciones_enteras
|
| 7251 |
|
| 7252 |
-
def
|
| 7253 |
|
| 7254 |
"""
|
| 7255 |
Aplica el algoritmo de aprendizaje supervisado Random Forest Regressor a
|
|
@@ -7359,6 +7343,108 @@ def tab_CM_rf(df: pd.DataFrame, pasos: int) -> list[int]:
|
|
| 7359 |
|
| 7360 |
return predicciones_enteras
|
| 7361 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7362 |
def tab_CM_lstm(df: pd.DataFrame, pasos: int) -> list[int]:
|
| 7363 |
|
| 7364 |
"""
|
|
@@ -10297,6 +10383,5 @@ if __name__ == "__main__":
|
|
| 10297 |
# allowed_paths DEBE incluir las rutas absolutas de las carpetas que contienen recursos
|
| 10298 |
app.launch(
|
| 10299 |
inbrowser=True,
|
| 10300 |
-
ssr_mode=False,
|
| 10301 |
allowed_paths=[current_dir, images_folder]
|
| 10302 |
)
|
|
|
|
| 64 |
# fin prg MAF
|
| 65 |
# endregion IMPORTACIÓN DE LIBRERÍAS
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
# region CONSTANTES Y DICCIONARIOS
|
| 69 |
# --- Constantes ---
|
| 70 |
+
DATA_PATH = "./datasets"
|
| 71 |
+
IMAGE_PATH = "./images"
|
| 72 |
FILE_MAP = {
|
| 73 |
"ARROZ": "arroz_depurado.csv",
|
| 74 |
"AVENA": "avena_depurado.csv",
|
|
|
|
| 100 |
YEAR_MIN = 1930 # Primer año de la serie de datos
|
| 101 |
YEAR_MAX = 2024 # ültimo año de la serie de datos
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
# Se cargan las descripciones de las variables de los datasets en un diccionario
|
| 104 |
# para títulos de gráficos de evolución de cultivos
|
| 105 |
+
variables = os.path.join(DATA_PATH, "nombres_largos.csv")
|
| 106 |
df_vars = pd.read_csv(variables, header=None, encoding='latin-1', sep=',')
|
| 107 |
dict_nlargos = df_vars.set_index(df_vars.columns[0])[df_vars.columns[1]].to_dict()
|
| 108 |
+
variables = os.path.join(DATA_PATH, "nombres_cortos.csv")
|
| 109 |
df_vars = pd.read_csv(variables, header=None, encoding='latin-1', sep=',')
|
| 110 |
dict_ncortos = df_vars.set_index(df_vars.columns[0])[df_vars.columns[1]].to_dict()
|
| 111 |
# endregion CONSTANTES Y DICCIONARIOS
|
|
|
|
| 3390 |
</div>
|
| 3391 |
"""
|
| 3392 |
elif n_obs > 4: # Mínimo de observaciones para una prueba con lags
|
| 3393 |
+
res = adfuller(serie_test, autolag='AIC', result_object=False)
|
| 3394 |
test_stat, p_value, lags_used, crit_values = res[0], res[1], res[2], res[4]
|
| 3395 |
|
| 3396 |
es_estacionaria = p_value < 0.05
|
|
|
|
| 3588 |
</div>
|
| 3589 |
"""
|
| 3590 |
if graf:
|
| 3591 |
+
return None
|
|
|
|
| 3592 |
else:
|
| 3593 |
+
return pd.DataFrame(), reporte, None, None, None, None, None
|
| 3594 |
|
| 3595 |
# Se verifica que la serie sea estacionaria (NO_EXISTE = sin prueba ADF, no se verificó estacionariedad)
|
| 3596 |
if d == NO_EXISTE:
|
|
|
|
| 3602 |
la prueba ADF para verificar ESTACIONARIEDAD.</div>
|
| 3603 |
"""
|
| 3604 |
if graf:
|
| 3605 |
+
return None
|
| 3606 |
else:
|
| 3607 |
+
return pd.DataFrame(), reporte, None, None, None, None, None
|
| 3608 |
|
| 3609 |
# Se verifica que el dataframe con la serie diferenciada ya exista
|
| 3610 |
if p == NO_EXISTE or q == NO_EXISTE:
|
|
|
|
| 3618 |
if graf:
|
| 3619 |
return None
|
| 3620 |
else:
|
| 3621 |
+
return pd.DataFrame(), reporte, None, None, None, None, None
|
| 3622 |
|
| 3623 |
# Se convierte el nombre corto del "indicador" a su nombre original
|
| 3624 |
ind_orig = next((k for k, v in dict_ncortos.items() if v == indicador), indicador)
|
| 3625 |
|
| 3626 |
# Se aguarda la unidad del indicador
|
| 3627 |
+
unidad_ind = {
|
| 3628 |
+
'SUP.SEMB.[ha]': ' ha',
|
| 3629 |
+
'SUP.COS.[ha]': ' ha',
|
| 3630 |
+
'REND.[kg/ha]': ' kg/ha',
|
| 3631 |
+
'PROD.[ton]': ' ton'
|
| 3632 |
+
}
|
| 3633 |
+
unidad = unidad_ind.get(indicador, "")
|
| 3634 |
|
| 3635 |
# Se convierte 'periodo' a formato datetime y establecerlo como índice con frecuencia,
|
| 3636 |
# porque así lo requiere el modelo ARIMA
|
|
|
|
| 3655 |
"<i>p</i> y <i>q</i> calculados.<br>"
|
| 3656 |
f"<i>p</i> = {p}; <i>q</i> = {q}.</div>"
|
| 3657 |
)
|
| 3658 |
+
return pd.DataFrame(), reporte, None, None, None, None, None
|
| 3659 |
|
| 3660 |
|
| 3661 |
|
|
|
|
| 3825 |
'Sup': intervalos.iloc[:, 1].values
|
| 3826 |
})
|
| 3827 |
|
| 3828 |
+
pred1, pred2, pred3, pred4, pred5 = df_plot_pred['Valor'].round(2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3829 |
|
| 3830 |
# Se agrega al df histórico el primer dato del df predicho para
|
| 3831 |
# que no quede un salto en el gráfico.
|
|
|
|
| 5309 |
|
| 5310 |
# region FUNCIONES PARA IMAGENES/VIDEOS EN BASE64 E INCLUSIÓN EN CÓDIGO CSS
|
| 5311 |
# Función para convertir imagen/video a Base64
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5312 |
def media_to_base64(media_path):
|
| 5313 |
+
if not os.path.exists(media_path):
|
|
|
|
|
|
|
| 5314 |
return ""
|
| 5315 |
+
with open(media_path, "rb") as media_file:
|
| 5316 |
+
return base64.b64encode(media_file.read()).decode('utf-8')
|
|
|
|
| 5317 |
|
| 5318 |
# Se lee el contenido del CSS externo para agregar
|
| 5319 |
# las líneas correspondientes a las imágenes de fondo
|
|
|
|
| 5331 |
img_path_2 = os.path.join(current_dir, "Images", "Title_bg.png")
|
| 5332 |
img_path_3 = os.path.join(current_dir, "Images", "Container_bg.png")
|
| 5333 |
img_path_4 = os.path.join(current_dir, "Images", "header_bg.png")
|
| 5334 |
+
img_path_5 = os.path.join(current_dir, "Images", "portrait_bg.png")
|
| 5335 |
+
vid_path_1 = os.path.join(current_dir, "Images", "portrait_bg.mp4")
|
| 5336 |
fondo_app = media_to_base64(img_path_1)
|
| 5337 |
fondo_titulo = media_to_base64(img_path_2)
|
| 5338 |
fondo_contenedor = media_to_base64(img_path_3)
|
| 5339 |
fondo_encabezado = media_to_base64(img_path_4)
|
| 5340 |
+
fondo_portada = media_to_base64(img_path_5)
|
| 5341 |
video_portada = media_to_base64(vid_path_1)
|
| 5342 |
|
| 5343 |
# Se agregan al CSS leído, las líneas que aplican las imágenes de fondo en BASE64,
|
|
|
|
| 5350 |
.custom-tab-2 {{ background-image: url('data:image/png;base64,{fondo_contenedor}') !important; }}
|
| 5351 |
.custom-tab-3 {{ background-image: url('data:image/png;base64,{fondo_contenedor}') !important; }}
|
| 5352 |
.header-tab {{ background-image: url('data:image/png;base64,{fondo_encabezado}') !important; }}
|
| 5353 |
+
.portrait-bg-1 {{ background-image: url('data:image/png;base64,{fondo_portada}') !important; }}
|
| 5354 |
.portrait-bg-2 {{ background-image: url('data:image/png;base64,{fondo_titulo}') !important; }}
|
| 5355 |
.modal-ayuda {{ background-image: url('data:image/png;base64,{fondo_contenedor}') !important; }}
|
| 5356 |
.modal-grafico {{ background-image: url('data:image/png;base64,{fondo_contenedor}') !important; }}
|
|
|
|
| 5586 |
ultimo_anio_historico = int(periodos_historicos_unicos[-1])
|
| 5587 |
|
| 5588 |
# 3. Mapeo de indicadores y definición de la variable objetivo (target)
|
| 5589 |
+
dict_ncortos = {
|
| 5590 |
+
"SUP.SEMB.[ha]": "sup_sem_ha",
|
| 5591 |
+
"SUP.COS.[ha]": "sup_cos_ha",
|
| 5592 |
+
"REND.[kg/ha]": "rend_kgxha",
|
| 5593 |
+
"PROD.[ton]": "prod_ton",
|
| 5594 |
+
}
|
| 5595 |
+
indicador = dict_ncortos.get(
|
| 5596 |
+
indicador_seleccionado, indicador_seleccionado
|
| 5597 |
+
)
|
| 5598 |
+
target = indicador
|
| 5599 |
|
| 5600 |
+
if target not in df_trabajo.columns:
|
| 5601 |
+
return (None, f"Error: No se encontró la columna objetivo '{target}'.",
|
| 5602 |
+
None, None, None,
|
| 5603 |
+
None, None, None, None, None, None, None, None,
|
| 5604 |
+
None, None, None, None, None)
|
| 5605 |
|
| 5606 |
+
unidad_ind = {
|
| 5607 |
+
"SUP.SEMB.[ha]": " ha",
|
| 5608 |
+
"SUP.COS.[ha]": " ha",
|
| 5609 |
+
"REND.[kg/ha]": " kg/ha",
|
| 5610 |
+
"PROD.[ton]": " ton",
|
| 5611 |
+
}
|
| 5612 |
+
unidad = unidad_ind.get(indicador_seleccionado, "")
|
| 5613 |
|
| 5614 |
# Separación de características (X) y variable objetivo (y)
|
| 5615 |
+
X = df_trabajo.drop(columns=[target, "periodo"], errors="ignore")
|
|
|
|
|
|
|
| 5616 |
y = df_trabajo[target]
|
|
|
|
| 5617 |
|
| 5618 |
# 4. División de datos (Train / Test) y entrenamiento del Random Forest
|
| 5619 |
X_train, X_test, y_train, y_test = train_test_split(
|
|
|
|
| 5895 |
Aplica Codificación Ordinal a fenómenos climáticos y One-Hot Encoding a variables políticas.
|
| 5896 |
"""
|
| 5897 |
# Mapeo de nombres cortos a columnas internas del dataset
|
| 5898 |
+
dict_ncortos = {
|
| 5899 |
+
'SUP.SEMB.[ha]': 'sup_sem_ha',
|
| 5900 |
+
'SUP.COS.[ha]': 'sup_cos_ha',
|
| 5901 |
+
'REND.[kg/ha]': 'rend_kgxha',
|
| 5902 |
+
'PROD.[ton]': 'prod_ton'
|
| 5903 |
+
}
|
| 5904 |
+
indicador = dict_ncortos.get(indicador_nc, indicador_nc)
|
| 5905 |
+
|
| 5906 |
+
unidad_ind = {
|
| 5907 |
+
'SUP.SEMB.[ha]': ' ha',
|
| 5908 |
+
'SUP.COS.[ha]': ' ha',
|
| 5909 |
+
'REND.[kg/ha]': ' kg/ha',
|
| 5910 |
+
'PROD.[ton]': ' ton'
|
| 5911 |
+
}
|
| 5912 |
+
unidad = unidad_ind.get(indicador_nc, "")
|
| 5913 |
|
| 5914 |
# Se filtra el dataset de cultivo
|
| 5915 |
df_cultivo, provincias = load_data(dataset_type)
|
|
|
|
| 6080 |
Mantiene la misma estructura de retorno y formato que la función original MLP.
|
| 6081 |
"""
|
| 6082 |
# Mapeo de nombres cortos a columnas internas del dataset
|
| 6083 |
+
dict_ncortos = {
|
| 6084 |
+
'SUP.SEMB.[ha]': 'sup_sem_ha',
|
| 6085 |
+
'SUP.COS.[ha]': 'sup_cos_ha',
|
| 6086 |
+
'REND.[kg/ha]': 'rend_kgxha',
|
| 6087 |
+
'PROD.[ton]': 'prod_ton'
|
| 6088 |
+
}
|
| 6089 |
+
indicador = dict_ncortos.get(indicador_nc, indicador_nc)
|
| 6090 |
+
|
| 6091 |
+
unidad_ind = {
|
| 6092 |
+
'SUP.SEMB.[ha]': ' ha',
|
| 6093 |
+
'SUP.COS.[ha]': ' ha',
|
| 6094 |
+
'REND.[kg/ha]': ' kg/ha',
|
| 6095 |
+
'PROD.[ton]': ' ton'
|
| 6096 |
+
}
|
| 6097 |
+
unidad = unidad_ind.get(indicador_nc, "")
|
| 6098 |
|
| 6099 |
# Se filtra el dataset de cultivo sin incorporar variables externas
|
| 6100 |
df_cultivo, provincias = load_data(dataset_type)
|
|
|
|
| 6110 |
res_df = res_df.sort_values('periodo').reset_index(drop=True)
|
| 6111 |
|
| 6112 |
# Extracción de la serie objetivo
|
| 6113 |
+
serie = res_df[indicador].astype(float).values.reshape(-1, 1)
|
|
|
|
| 6114 |
n_obs = len(serie)
|
| 6115 |
|
| 6116 |
# 4. División Hold-Out Cronológica (los últimos 5 años o 3 se reservan para prueba)
|
|
|
|
| 6990 |
# Manejo de fallos o combinaciones vacías
|
| 6991 |
if errores or not combinaciones: # Retorna un DataFrame vacío
|
| 6992 |
return pd.DataFrame(columns=["PROVINCIA", "DEPARTAMENTO",
|
| 6993 |
+
"INIC", "FIN", "AÑOS", "ELIM", "IMP", "UTIL",
|
| 6994 |
"HOLT-WINTERS", "ARIMA", "BOSQUES ALEATORIOS", "RED LSTM"])
|
| 6995 |
|
| 6996 |
# Descartar el elemento 'cultivo' extrayendo únicamente 'provincia' y 'departamento'
|
|
|
|
| 7000 |
df_predicciones = pd.DataFrame(combinaciones_filtradas, columns=["PROVINCIA", "DEPARTAMENTO"])
|
| 7001 |
|
| 7002 |
# Inicializar las columnas de los modelos predictivos con el valor por defecto "---"
|
| 7003 |
+
columnas_data = ["INIC", "FIN", "AÑOS", "ELIM", "IMP", "UTIL",
|
| 7004 |
"HOLT-WINTERS", "ARIMA", "BOSQUES ALEATORIOS", "RED LSTM"]
|
| 7005 |
for col in columnas_data:
|
| 7006 |
df_predicciones[col] = "---"
|
|
|
|
| 7024 |
df_predicciones.at[idx, "AÑOS"] = str(serie)
|
| 7025 |
df_predicciones.at[idx, "ELIM"] = str(elim)
|
| 7026 |
df_predicciones.at[idx, "IMP"] = str(imp)
|
| 7027 |
+
df_predicciones.at[idx, "UTIL"] = str(serie - elim + imp)
|
| 7028 |
|
| 7029 |
# Se extraen los últimos 3 valores de la serie histórica
|
| 7030 |
ultimos_historicos: List[float] = df_preparado.iloc[-3:, 1].astype(float).tolist()
|
|
|
|
| 7233 |
|
| 7234 |
return predicciones_enteras
|
| 7235 |
|
| 7236 |
+
def tab_CM_rf_defectuosa(df: pd.DataFrame, pasos: int) -> list[int]:
|
| 7237 |
|
| 7238 |
"""
|
| 7239 |
Aplica el algoritmo de aprendizaje supervisado Random Forest Regressor a
|
|
|
|
| 7343 |
|
| 7344 |
return predicciones_enteras
|
| 7345 |
|
| 7346 |
+
def tab_CM_rf(df: pd.DataFrame, pasos: int) -> list[int]:
|
| 7347 |
+
"""
|
| 7348 |
+
Aplica el algoritmo de aprendizaje supervisado Random Forest Regressor a
|
| 7349 |
+
una serie temporal y predice valores futuros. Transforma la serie en un
|
| 7350 |
+
problema supervisado mediante la creación de variables desfasadas (lags),
|
| 7351 |
+
evalúa la profundidad optima del historial y realiza una predicción
|
| 7352 |
+
iterativa autoregresiva, utilizando un esquema de validación temporal
|
| 7353 |
+
para evitar sobreajuste.
|
| 7354 |
+
Parámetros:
|
| 7355 |
+
df: pd.DataFrame (con dos columnas: tiempo, indicador agrícola)
|
| 7356 |
+
pasos: int (cantidad de periodos a predecir)
|
| 7357 |
+
Devuelve:
|
| 7358 |
+
list[int]: lista de valores futuros predichos, redondeados sin decimales.
|
| 7359 |
+
"""
|
| 7360 |
+
try:
|
| 7361 |
+
# Asegurar la extracción y tipo de la serie temporal
|
| 7362 |
+
serie = df.iloc[:, 1].astype(float).values
|
| 7363 |
+
n_obs = len(serie)
|
| 7364 |
+
if n_obs < 5:
|
| 7365 |
+
return None
|
| 7366 |
+
|
| 7367 |
+
pasos_futuros = pasos
|
| 7368 |
+
max_lags = min(5, max(1, n_obs // 4))
|
| 7369 |
+
|
| 7370 |
+
def crear_dataset_supervisado(
|
| 7371 |
+
datos: np.ndarray, n_lags: int
|
| 7372 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 7373 |
+
X, y = [], []
|
| 7374 |
+
for i in range(len(datos) - n_lags):
|
| 7375 |
+
X.append(datos[i : (i + n_lags)])
|
| 7376 |
+
y.append(datos[i + n_lags])
|
| 7377 |
+
return np.array(X), np.array(y)
|
| 7378 |
+
|
| 7379 |
+
# 2. Selección óptima de lags utilizando validación fuera de muestra (Train/Validation Split temporal)
|
| 7380 |
+
best_mse = float("inf")
|
| 7381 |
+
best_lags = 1
|
| 7382 |
+
|
| 7383 |
+
# Reservamos el último 20% de los datos como conjunto de validación temporal
|
| 7384 |
+
split_idx = int(n_obs * 0.8)
|
| 7385 |
+
|
| 7386 |
+
for lags in range(1, max_lags + 1):
|
| 7387 |
+
X_temp, y_temp = crear_dataset_supervisado(serie, lags)
|
| 7388 |
+
|
| 7389 |
+
if len(X_temp) < 4:
|
| 7390 |
+
continue
|
| 7391 |
+
|
| 7392 |
+
# Separar en entrenamiento y validación respetando el orden temporal
|
| 7393 |
+
train_mask = [
|
| 7394 |
+
i < split_idx - lags for i in range(len(X_temp))
|
| 7395 |
+
]
|
| 7396 |
+
if sum(train_mask) < 2 or sum(train_mask) == len(X_temp):
|
| 7397 |
+
# Si el split no es viable, evaluamos con el total pero penalizamos complejidad
|
| 7398 |
+
X_train_v, y_train_v = X_temp, y_temp
|
| 7399 |
+
X_val_v, y_val_v = X_temp, y_temp
|
| 7400 |
+
else:
|
| 7401 |
+
X_train_v, y_train_v = (
|
| 7402 |
+
X_temp[train_mask],
|
| 7403 |
+
y_temp[train_mask],
|
| 7404 |
+
)
|
| 7405 |
+
X_val_v, y_val_v = (
|
| 7406 |
+
X_temp[~np.array(train_mask)],
|
| 7407 |
+
y_temp[~np.array(train_mask)],
|
| 7408 |
+
)
|
| 7409 |
+
|
| 7410 |
+
rf_eval = RandomForestRegressor(
|
| 7411 |
+
n_estimators=50, max_depth=4, random_state=42
|
| 7412 |
+
)
|
| 7413 |
+
rf_eval.fit(X_train_v, y_train_v)
|
| 7414 |
+
pred_val = rf_eval.predict(X_val_v)
|
| 7415 |
+
|
| 7416 |
+
# Error cuadrático medio de validación
|
| 7417 |
+
mse_val = np.mean((y_val_v - pred_val) ** 2)
|
| 7418 |
+
|
| 7419 |
+
if mse_val < best_mse:
|
| 7420 |
+
best_mse = mse_val
|
| 7421 |
+
best_lags = lags
|
| 7422 |
+
|
| 7423 |
+
# 3. Reentrenamiento del modelo final con todo el dataset usando los mejores lags
|
| 7424 |
+
X_final, y_final = crear_dataset_supervisado(serie, best_lags)
|
| 7425 |
+
|
| 7426 |
+
modelo_rf = RandomForestRegressor(
|
| 7427 |
+
n_estimators=100, max_depth=6, random_state=42, n_jobs=-1
|
| 7428 |
+
)
|
| 7429 |
+
modelo_rf.fit(X_final, y_final)
|
| 7430 |
+
|
| 7431 |
+
# 4. Generación de pronósticos fuera de muestra (Estrategia Autoregresiva)
|
| 7432 |
+
predicciones = []
|
| 7433 |
+
ventana_actual = list(serie[-best_lags:])
|
| 7434 |
+
|
| 7435 |
+
for _ in range(pasos_futuros):
|
| 7436 |
+
input_vector = np.array(ventana_actual[-best_lags:]).reshape(1, -1)
|
| 7437 |
+
pred_paso = modelo_rf.predict(input_vector)[0]
|
| 7438 |
+
predicciones.append(pred_paso)
|
| 7439 |
+
ventana_actual.append(pred_paso)
|
| 7440 |
+
|
| 7441 |
+
# 5. Formateo de los resultados a enteros sin decimales
|
| 7442 |
+
return [int(np.round(val)) for val in predicciones]
|
| 7443 |
+
|
| 7444 |
+
except Exception:
|
| 7445 |
+
# En caso de excepción crítica, se retorna el último valor sostenido en el horizonte
|
| 7446 |
+
ultimo_valor = int(np.round(df.iloc[-1, 1]))
|
| 7447 |
+
return [ultimo_valor] * pasos
|
| 7448 |
def tab_CM_lstm(df: pd.DataFrame, pasos: int) -> list[int]:
|
| 7449 |
|
| 7450 |
"""
|
|
|
|
| 10383 |
# allowed_paths DEBE incluir las rutas absolutas de las carpetas que contienen recursos
|
| 10384 |
app.launch(
|
| 10385 |
inbrowser=True,
|
|
|
|
| 10386 |
allowed_paths=[current_dir, images_folder]
|
| 10387 |
)
|
requirements.txt
CHANGED
|
Binary files a/requirements.txt and b/requirements.txt differ
|
|
|
style.css
CHANGED
|
@@ -36,7 +36,6 @@
|
|
| 36 |
background-attachment: fixed !important;
|
| 37 |
background-repeat: no-repeat !important;
|
| 38 |
background-position: center !important;
|
| 39 |
-
background: transparent !important;
|
| 40 |
}
|
| 41 |
|
| 42 |
|
|
|
|
| 36 |
background-attachment: fixed !important;
|
| 37 |
background-repeat: no-repeat !important;
|
| 38 |
background-position: center !important;
|
|
|
|
| 39 |
}
|
| 40 |
|
| 41 |
|
varianza.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
|
| 4 |
+
# Configuración general de estilo con fondo blanco e igualdad de dimensiones
|
| 5 |
+
plt.style.use('default')
|
| 6 |
+
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 7 |
+
fig.patch.set_facecolor('white')
|
| 8 |
+
|
| 9 |
+
# -------------------------------------------------------------
|
| 10 |
+
# 1. Generación de datos sintéticos base (Curva senoidal con ruido)
|
| 11 |
+
# -------------------------------------------------------------
|
| 12 |
+
np.random.seed(42)
|
| 13 |
+
X = np.linspace(0, 1, 60)
|
| 14 |
+
y = np.sin(2 * np.pi * X) + np.random.normal(0, 0.15, len(X))
|
| 15 |
+
|
| 16 |
+
X_smooth = np.linspace(0, 1, 200)
|
| 17 |
+
|
| 18 |
+
# -------------------------------------------------------------
|
| 19 |
+
# Gráfico 1: Varianza Adecuada (Modelado equilibrado)
|
| 20 |
+
# -------------------------------------------------------------
|
| 21 |
+
axes[0, 0].scatter(X, y, color='gray', alpha=0.6, s=30)
|
| 22 |
+
poly3 = np.polyfit(X, y, 3)
|
| 23 |
+
y_poly3 = np.polyval(poly3, X_smooth)
|
| 24 |
+
axes[0, 0].plot(X_smooth, y_poly3, color='red', linewidth=2.5, label='Curva de ajuste adecuada')
|
| 25 |
+
axes[0, 0].set_title('Varianza Adecuada (Modelo Equilibrado)', fontsize=12, fontweight='bold')
|
| 26 |
+
axes[0, 0].set_xlabel('x')
|
| 27 |
+
axes[0, 0].set_ylabel('y')
|
| 28 |
+
axes[0, 0].legend(loc='upper right')
|
| 29 |
+
axes[0, 0].grid(True, linestyle='--', alpha=0.3)
|
| 30 |
+
axes[0, 0].set_facecolor('white')
|
| 31 |
+
|
| 32 |
+
# -------------------------------------------------------------
|
| 33 |
+
# Gráfico 2: Varianza Alta (Sobreajuste - Sin la curva azul)
|
| 34 |
+
# -------------------------------------------------------------
|
| 35 |
+
axes[0, 1].scatter(X, y, color='gray', alpha=0.6, s=30)
|
| 36 |
+
# Se omite intencionalmente la curva de ajuste excesiva (azul) según los requerimientos
|
| 37 |
+
axes[0, 1].set_title('Varianza Alta (Sobreajuste - Sin curva)', fontsize=12, fontweight='bold')
|
| 38 |
+
axes[0, 1].set_xlabel('x')
|
| 39 |
+
axes[0, 1].set_ylabel('y')
|
| 40 |
+
axes[0, 1].grid(True, linestyle='--', alpha=0.3)
|
| 41 |
+
axes[0, 1].set_facecolor('white')
|
| 42 |
+
|
| 43 |
+
# -------------------------------------------------------------
|
| 44 |
+
# Datos y modelos para el análisis de Sesgo (Tendencia cuadrática)
|
| 45 |
+
# -------------------------------------------------------------
|
| 46 |
+
X_b = np.linspace(0, 1, 40)
|
| 47 |
+
y_b = 3 * (X_b ** 2) + np.random.normal(0, 0.1, len(X_b))
|
| 48 |
+
X_b_smooth = np.linspace(0, 1, 100)
|
| 49 |
+
|
| 50 |
+
# -------------------------------------------------------------
|
| 51 |
+
# Gráfico 3: Sesgo Adecuado (Bajo sesgo / Ajuste polinómico de grado 2)
|
| 52 |
+
# -------------------------------------------------------------
|
| 53 |
+
axes[1, 0].scatter(X_b, y_b, color='gray', alpha=0.6, s=30)
|
| 54 |
+
poly_b2 = np.polyfit(X_b, y_b, 2)
|
| 55 |
+
y_b2 = np.polyval(poly_b2, X_b_smooth)
|
| 56 |
+
axes[1, 0].plot(X_b_smooth, y_b2, color='saddlebrown', linewidth=2.5, label='Curva de ajuste adecuada')
|
| 57 |
+
axes[1, 0].set_title('Sesgo Adecuado (Bajo sesgo)', fontsize=12, fontweight='bold')
|
| 58 |
+
axes[1, 0].set_xlabel('x')
|
| 59 |
+
axes[1, 0].set_ylabel('y')
|
| 60 |
+
axes[1, 0].legend(loc='upper left')
|
| 61 |
+
axes[1, 0].grid(True, linestyle='--', alpha=0.3)
|
| 62 |
+
axes[1, 0].set_facecolor('white')
|
| 63 |
+
|
| 64 |
+
# -------------------------------------------------------------
|
| 65 |
+
# Gráfico 4: Sesgo Alto (Subajuste / Ajuste lineal)
|
| 66 |
+
# -------------------------------------------------------------
|
| 67 |
+
axes[1, 1].scatter(X_b, y_b, color='gray', alpha=0.6, s=30)
|
| 68 |
+
poly_b1 = np.polyfit(X_b, y_b, 1)
|
| 69 |
+
y_b1 = np.polyval(poly_b1, X_b_smooth)
|
| 70 |
+
axes[1, 1].plot(X_b_smooth, y_b1, color='purple', linewidth=2.5, label='Línea de ajuste lineal (Subajuste)')
|
| 71 |
+
axes[1, 1].set_title('Sesgo Alto (Subajuste)', fontsize=12, fontweight='bold')
|
| 72 |
+
axes[1, 1].set_xlabel('x')
|
| 73 |
+
axes[1, 1].set_ylabel('y')
|
| 74 |
+
axes[1, 1].legend(loc='upper left')
|
| 75 |
+
axes[1, 1].grid(True, linestyle='--', alpha=0.3)
|
| 76 |
+
axes[1, 1].set_facecolor('white')
|
| 77 |
+
|
| 78 |
+
# Ajuste final de diseño y renderizado
|
| 79 |
+
plt.tight_layout()
|
| 80 |
+
plt.show()
|