feat: initial ski predictor system

Hybrid ML + rules prediction system for 3 Asturian ski stations
(Pajares, San Isidro, Fuentes de Invierno).

- Weather data from Open-Meteo (historical + forecast)
- Station scraping from infonieve.es (live + 16 seasons historical TSV)
- Feature engineering: rolling snow, calendar, temperature/pressure trends
- ML models: RandomForest (open/close), GradientBoosting (km), LightGBM (crowd)
- Rules engine: wind closure, snow depth, rain+heat, heavy snow
- YOLOv8 webcam crowd detection (cars, people in parking/lifts)
- Telegram bot with /pajares, /sanisidro, /fuentes commands
- Daily cron pipeline for automated data collection and predictions
- Deployment guide with systemd service and cron setup
This commit is contained in:
dasemu committed 2026-03-12 14:51:32 +01:00
commit 1afe2b73e0
34 files changed
+7201

No files matched your search

+384
View File
@@ -0,0 +1,384 @@
"""Evaluate trained ski-condition prediction models.
Loads each model from ml/models/, runs evaluation on a held-out test split
of the processed feature dataset, computes task-appropriate metrics, and
writes a JSON report to ml/models/evaluation_report.json.
Classification metrics: accuracy, precision, recall, F1 (macro), AUC.
Regression metrics: MAE, RMSE, R2.
"""
import json
import logging
from pathlib import Path
from typing import Any
import joblib
import numpy as np
import pandas as pd
from sklearn.metrics import (
accuracy_score,
f1_score,
mean_absolute_error,
precision_score,
r2_score,
recall_score,
roc_auc_score,
)
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
_REPO_ROOT = Path(__file__).resolve().parents[1]
DATASET_PATH = _REPO_ROOT / "data" / "processed" / "dataset_featured.csv"
MODELS_DIR = _REPO_ROOT / "ml" / "models"
REPORT_PATH = MODELS_DIR / "evaluation_report.json"
# Test split fraction. With a small dataset 20 % gives at least a handful of
# samples per class while keeping enough for stratification.
TEST_SIZE = 0.20
RANDOM_STATE = 42
# Targets and their task types
TARGETS: dict[str, str] = {
"station_open": "binary",
"km_open": "regression",
"crowd_level": "multiclass",
}
# Ordered crowd-level labels – must match what ModelTrainer used
CROWD_LEVEL_LABELS = ["low", "medium", "high"]
class ModelEvaluator:
"""Evaluate persisted ski-condition models against a held-out test set.
Parameters
----------
dataset_path:
Path to the processed feature CSV.
models_dir:
Directory containing the trained ``.joblib`` model files.
test_size:
Fraction of the dataset to use as the test set.
"""
def __init__(
self,
dataset_path: Path | str = DATASET_PATH,
models_dir: Path | str = MODELS_DIR,
test_size: float = TEST_SIZE,
) -> None:
self.dataset_path = Path(dataset_path)
self.models_dir = Path(models_dir)
self.test_size = test_size
self._df: pd.DataFrame | None = None
self._feature_columns: list[str] = []
self._models: dict[str, Any] = {}
self._label_encoder: LabelEncoder | None = None
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def evaluate_all(self) -> dict[str, dict[str, float]]:
"""Evaluate all trained models and persist a JSON report.
Returns
-------
dict
``{target_name: {metric_name: value, ...}}``
Side effects
------------
Writes ``ml/models/evaluation_report.json``.
"""
self._load_dataset()
self._load_models()
report: dict[str, Any] = {}
for target, task_type in TARGETS.items():
if target not in self._models:
logger.warning(
"No model found for target '%s'; skipping evaluation.",
target,
)
continue
logger.info("Evaluating model for target: %s", target)
metrics = self._evaluate_single(target, task_type)
report[target] = metrics
logger.info("Metrics for %s: %s", target, metrics)
self._save_report(report)
return report
def get_feature_importance(self, model_name: str) -> list[tuple[str, float]]:
"""Return feature importances for a trained model, sorted descending.
This method reads the pre-computed importance JSON written by
``ModelTrainer`` rather than recomputing from the model, so the
trainer must have been run first.
Parameters
----------
model_name:
One of ``station_open``, ``km_open``, or ``crowd_level``.
Returns
-------
list of (feature_name, importance) tuples sorted by importance descending.
Raises
------
FileNotFoundError
If the corresponding JSON importance file does not exist.
ValueError
If *model_name* is not a recognised target.
"""
if model_name not in TARGETS:
raise ValueError(
f"Unknown model name '{model_name}'. "
f"Valid names: {list(TARGETS.keys())}"
)
importance_path = self.models_dir / f"{model_name}_feature_importances.json"
if not importance_path.exists():
raise FileNotFoundError(
f"Feature importance file not found: {importance_path}. "
"Run train_model.py first."
)
with open(importance_path, encoding="utf-8") as fh:
raw: dict[str, float] = json.load(fh)
sorted_importances = sorted(raw.items(), key=lambda kv: kv[1], reverse=True)
return sorted_importances
# ------------------------------------------------------------------
# Private helpers
# ------------------------------------------------------------------
def _load_dataset(self) -> None:
"""Load the processed dataset and derive feature column names."""
if not self.dataset_path.exists():
raise FileNotFoundError(
f"Processed dataset not found at {self.dataset_path}. "
"Run the pipeline first."
)
logger.info("Loading dataset from %s", self.dataset_path)
self._df = pd.read_csv(self.dataset_path, parse_dates=["date"])
non_feature_cols = set(TARGETS.keys()) | {"date", "station"}
self._feature_columns = [
col for col in self._df.columns if col not in non_feature_cols
]
logger.info(
"Dataset loaded: %d rows, %d features",
len(self._df),
len(self._feature_columns),
)
def _load_models(self) -> None:
"""Load all model files found in models_dir."""
for target in TARGETS:
model_path = self.models_dir / f"{target}_model.joblib"
if model_path.exists():
self._models[target] = joblib.load(model_path)
logger.info("Loaded model: %s", model_path.name)
else:
logger.warning("Model file not found: %s", model_path)
# Load the label encoder for crowd_level if available
encoder_path = self.models_dir / "crowd_level_label_encoder.joblib"
if encoder_path.exists():
self._label_encoder = joblib.load(encoder_path)
logger.info("Loaded crowd_level LabelEncoder.")
else:
logger.warning(
"crowd_level_label_encoder.joblib not found; "
"crowd_level evaluation may fail."
)
def _prepare_test_split(
self, target: str
) -> tuple[pd.DataFrame, np.ndarray]:
"""Return (X_test, y_test) for a given target using a fixed split.
The split is deterministic via ``RANDOM_STATE`` so repeated calls
for different targets use the same test rows.
"""
assert self._df is not None
df = self._df.dropna(subset=[target]).copy()
if len(df) < 5:
raise RuntimeError(
f"Too few non-null rows ({len(df)}) for target '{target}' "
"to create a meaningful train/test split."
)
X = df[self._feature_columns].fillna(
df[self._feature_columns].median(numeric_only=True)
)
if target == "crowd_level":
if self._label_encoder is None:
le = LabelEncoder()
le.fit(CROWD_LEVEL_LABELS)
self._label_encoder = le
y_encoded = self._label_encoder.transform(
df[target].astype(str)
)
y = y_encoded
stratify = y
else:
y = df[target].values
stratify = y if target == "station_open" else None
_, X_test, _, y_test = train_test_split(
X,
y,
test_size=self.test_size,
random_state=RANDOM_STATE,
stratify=stratify,
)
return X_test, y_test
def _evaluate_single(
self, target: str, task_type: str
) -> dict[str, float]:
"""Compute evaluation metrics for one model on the test split."""
model = self._models[target]
X_test, y_test = self._prepare_test_split(target)
y_pred = model.predict(X_test)
if task_type == "binary":
metrics = self._classification_metrics(
model, X_test, y_test, y_pred, multiclass=False
)
elif task_type == "multiclass":
metrics = self._classification_metrics(
model, X_test, y_test, y_pred, multiclass=True
)
else:
metrics = self._regression_metrics(y_test, y_pred)
metrics["n_test_samples"] = int(len(y_test))
return metrics
@staticmethod
def _classification_metrics(
model: Any,
X_test: pd.DataFrame,
y_test: np.ndarray,
y_pred: np.ndarray,
*,
multiclass: bool,
) -> dict[str, float]:
"""Compute accuracy, precision, recall, F1, and AUC."""
average = "macro" if multiclass else "binary"
metrics: dict[str, float] = {
"accuracy": round(float(accuracy_score(y_test, y_pred)), 4),
"precision": round(
float(precision_score(y_test, y_pred, average=average, zero_division=0)),
4,
),
"recall": round(
float(recall_score(y_test, y_pred, average=average, zero_division=0)),
4,
),
"f1": round(
float(f1_score(y_test, y_pred, average=average, zero_division=0)),
4,
),
}
# AUC requires probability estimates
try:
if hasattr(model, "predict_proba"):
y_proba = model.predict_proba(X_test)
if multiclass:
auc = roc_auc_score(
y_test, y_proba, multi_class="ovr", average="weighted"
)
else:
auc = roc_auc_score(y_test, y_proba[:, 1])
metrics["auc"] = round(float(auc), 4)
except Exception as exc: # noqa: BLE001
logger.warning("Could not compute AUC for model: %s", exc)
return metrics
@staticmethod
def _regression_metrics(
y_test: np.ndarray, y_pred: np.ndarray
) -> dict[str, float]:
"""Compute MAE, RMSE, and R2."""
mae = mean_absolute_error(y_test, y_pred)
rmse = float(np.sqrt(mean_squared_error_compat(y_test, y_pred)))
r2 = r2_score(y_test, y_pred)
return {
"mae": round(float(mae), 4),
"rmse": round(rmse, 4),
"r2": round(float(r2), 4),
}
def _save_report(self, report: dict[str, Any]) -> None:
"""Write the evaluation report to disk as JSON."""
self.models_dir.mkdir(parents=True, exist_ok=True)
with open(REPORT_PATH, "w", encoding="utf-8") as fh:
json.dump(report, fh, indent=2)
logger.info("Evaluation report saved to %s", REPORT_PATH)
# ---------------------------------------------------------------------------
# Compatibility shim: sklearn removed mean_squared_error's squared kwarg
# in 1.4 and added root_mean_squared_error in 1.4.
# ---------------------------------------------------------------------------
try:
from sklearn.metrics import root_mean_squared_error as _rmse_fn
def mean_squared_error_compat(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Return RMSE using the sklearn API available in the environment."""
return float(_rmse_fn(y_true, y_pred))
except ImportError:
from sklearn.metrics import mean_squared_error as _mse_fn # type: ignore[assignment]
def mean_squared_error_compat(y_true: np.ndarray, y_pred: np.ndarray) -> float: # type: ignore[misc]
"""Return RMSE using the sklearn API available in the environment."""
return float(np.sqrt(_mse_fn(y_true, y_pred)))
# ---------------------------------------------------------------------------
# CLI entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
evaluator = ModelEvaluator()
results = evaluator.evaluate_all()
print("\nEvaluation results:")
for target, metrics in results.items():
print(f" {target}: {metrics}")
print("\nFeature importances (top 5 per model):")
for target in TARGETS:
try:
importances = evaluator.get_feature_importance(target)
top5 = importances[:5]
print(f" {target}: {top5}")
except FileNotFoundError as exc:
print(f" {target}: {exc}")