mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
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:
commit
1afe2b73e0
34 files changed
+7201
No files matched your search
@@ -0,0 +1,356 @@
|
||||
"""Train predictive models for ski station conditions.
|
||||
|
||||
Trains three models against the processed feature dataset:
|
||||
- station_open: binary classification (RandomForestClassifier)
|
||||
- km_open: regression (GradientBoostingRegressor)
|
||||
- crowd_level: multi-class classification (LGBMClassifier)
|
||||
|
||||
Models and feature importances are persisted under ml/models/ via joblib.
|
||||
Cross-validation (5-fold stratified for classifiers, KFold for regression)
|
||||
is used throughout to compensate for the small dataset size.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from lightgbm import LGBMClassifier
|
||||
from sklearn.ensemble import GradientBoostingRegressor, RandomForestClassifier
|
||||
from sklearn.model_selection import KFold, StratifiedKFold, cross_validate
|
||||
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"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Model registry
|
||||
# ---------------------------------------------------------------------------
|
||||
# Maps each target to a (model_instance, task_type) tuple.
|
||||
# task_type is one of: "binary", "regression", "multiclass"
|
||||
MODEL_REGISTRY: dict[str, tuple[Any, str]] = {
|
||||
"station_open": (
|
||||
RandomForestClassifier(
|
||||
n_estimators=200,
|
||||
max_depth=8,
|
||||
min_samples_leaf=2,
|
||||
class_weight="balanced",
|
||||
random_state=42,
|
||||
n_jobs=-1,
|
||||
),
|
||||
"binary",
|
||||
),
|
||||
"km_open": (
|
||||
GradientBoostingRegressor(
|
||||
n_estimators=200,
|
||||
max_depth=4,
|
||||
learning_rate=0.05,
|
||||
subsample=0.8,
|
||||
min_samples_leaf=2,
|
||||
random_state=42,
|
||||
),
|
||||
"regression",
|
||||
),
|
||||
"crowd_level": (
|
||||
LGBMClassifier(
|
||||
n_estimators=200,
|
||||
max_depth=6,
|
||||
learning_rate=0.05,
|
||||
num_leaves=31,
|
||||
min_child_samples=5,
|
||||
class_weight="balanced",
|
||||
random_state=42,
|
||||
verbose=-1,
|
||||
),
|
||||
"multiclass",
|
||||
),
|
||||
}
|
||||
|
||||
# Ordered crowd-level labels used for LabelEncoder consistency
|
||||
CROWD_LEVEL_LABELS = ["low", "medium", "high"]
|
||||
|
||||
N_CV_FOLDS = 5
|
||||
|
||||
|
||||
class ModelTrainer:
|
||||
"""Train and persist ski-condition prediction models.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
dataset_path:
|
||||
Path to the processed feature CSV. Defaults to
|
||||
``data/processed/dataset_featured.csv`` relative to the repo root.
|
||||
models_dir:
|
||||
Directory where trained models and importances are saved. Defaults to
|
||||
``ml/models/`` relative to the repo root.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dataset_path: Path | str = DATASET_PATH,
|
||||
models_dir: Path | str = MODELS_DIR,
|
||||
) -> None:
|
||||
self.dataset_path = Path(dataset_path)
|
||||
self.models_dir = Path(models_dir)
|
||||
self.models_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self._df: pd.DataFrame | None = None
|
||||
self._feature_columns: list[str] = []
|
||||
self._label_encoder: LabelEncoder | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def train_all(self) -> dict[str, dict[str, float]]:
|
||||
"""Train all three models and return their cross-validation scores.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
``{target_name: {metric_name: score, ...}}``
|
||||
"""
|
||||
self._load_dataset()
|
||||
|
||||
cv_results: dict[str, dict[str, float]] = {}
|
||||
for target, (_, task_type) in MODEL_REGISTRY.items():
|
||||
logger.info("Training model for target: %s", target)
|
||||
cv_results[target] = self.train_model(target, task_type)
|
||||
|
||||
logger.info("All models trained successfully.")
|
||||
return cv_results
|
||||
|
||||
def train_model(self, target: str, model_type: str) -> dict[str, float]:
|
||||
"""Train a single model, evaluate it with cross-validation, and save it.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
target:
|
||||
Column name of the prediction target (``station_open``,
|
||||
``km_open``, or ``crowd_level``).
|
||||
model_type:
|
||||
One of ``"binary"``, ``"multiclass"``, or ``"regression"``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
Cross-validation metric averages for the model.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If *target* or *model_type* are not recognised.
|
||||
RuntimeError
|
||||
If the dataset has not been loaded yet (call ``train_all()`` or
|
||||
``_load_dataset()`` first).
|
||||
"""
|
||||
if self._df is None:
|
||||
self._load_dataset()
|
||||
|
||||
if target not in MODEL_REGISTRY:
|
||||
raise ValueError(
|
||||
f"Unknown target '{target}'. "
|
||||
f"Valid targets: {list(MODEL_REGISTRY.keys())}"
|
||||
)
|
||||
|
||||
valid_types = {"binary", "multiclass", "regression"}
|
||||
if model_type not in valid_types:
|
||||
raise ValueError(
|
||||
f"Unknown model_type '{model_type}'. Valid: {valid_types}"
|
||||
)
|
||||
|
||||
X, y = self._prepare_features_and_target(target)
|
||||
model, _ = MODEL_REGISTRY[target]
|
||||
|
||||
# Cross-validate before final fit on all data
|
||||
cv_scores = self._cross_validate(model, X, y, model_type)
|
||||
logger.info("CV scores for %s: %s", target, cv_scores)
|
||||
|
||||
# Final fit on the full available dataset
|
||||
model.fit(X, y)
|
||||
logger.info("Final fit complete for target: %s", target)
|
||||
|
||||
self._save_model(model, target)
|
||||
self._save_feature_importances(model, target)
|
||||
|
||||
return cv_scores
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_dataset(self) -> None:
|
||||
"""Load the processed dataset from disk and derive feature columns."""
|
||||
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"])
|
||||
|
||||
target_cols = set(MODEL_REGISTRY.keys())
|
||||
# Exclude date, station identifiers, target aliases, and non-numeric
|
||||
# categorical columns that cannot be used as model inputs directly.
|
||||
non_feature_cols = target_cols | {
|
||||
"date",
|
||||
"station",
|
||||
"station_id",
|
||||
# open_status is an alias for station_open (target); exclude it
|
||||
"open_status",
|
||||
# snow_quality is free-text; exclude until encoding is added
|
||||
"snow_quality",
|
||||
# season is a string label, not a numeric feature
|
||||
"season",
|
||||
}
|
||||
# Also exclude any remaining object/string columns to prevent sklearn errors
|
||||
string_cols = set(
|
||||
self._df.select_dtypes(include=["object", "string"]).columns
|
||||
)
|
||||
non_feature_cols |= string_cols
|
||||
|
||||
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 _prepare_features_and_target(
|
||||
self, target: str
|
||||
) -> tuple[pd.DataFrame, pd.Series | np.ndarray]:
|
||||
"""Return (X, y) with rows that have a valid target value."""
|
||||
assert self._df is not None # guaranteed by callers
|
||||
|
||||
df = self._df.dropna(subset=[target]).copy()
|
||||
if len(df) == 0:
|
||||
raise RuntimeError(
|
||||
f"No non-null rows found for target '{target}' in the dataset."
|
||||
)
|
||||
|
||||
X = df[self._feature_columns].copy()
|
||||
X = X.fillna(X.median(numeric_only=True))
|
||||
|
||||
if target == "crowd_level":
|
||||
# Encode string labels to integers in a stable order
|
||||
le = LabelEncoder()
|
||||
le.fit(CROWD_LEVEL_LABELS)
|
||||
y = le.transform(df[target].astype(str))
|
||||
self._label_encoder = le
|
||||
# Persist the encoder so the evaluator can decode predictions
|
||||
joblib.dump(le, self.models_dir / "crowd_level_label_encoder.joblib")
|
||||
logger.debug("LabelEncoder classes: %s", list(le.classes_))
|
||||
else:
|
||||
y = df[target].values
|
||||
|
||||
return X, y
|
||||
|
||||
def _cross_validate(
|
||||
self,
|
||||
model: Any,
|
||||
X: pd.DataFrame,
|
||||
y: pd.Series | np.ndarray,
|
||||
model_type: str,
|
||||
) -> dict[str, float]:
|
||||
"""Run k-fold cross-validation and return mean scores.
|
||||
|
||||
Uses StratifiedKFold for classification targets so that class
|
||||
proportions are preserved in each fold.
|
||||
"""
|
||||
if model_type in {"binary", "multiclass"}:
|
||||
scoring = {
|
||||
"accuracy": "accuracy",
|
||||
"f1_macro": "f1_macro",
|
||||
"roc_auc": (
|
||||
"roc_auc"
|
||||
if model_type == "binary"
|
||||
else "roc_auc_ovr_weighted"
|
||||
),
|
||||
}
|
||||
cv = StratifiedKFold(
|
||||
n_splits=N_CV_FOLDS, shuffle=True, random_state=42
|
||||
)
|
||||
else:
|
||||
scoring = {
|
||||
"neg_mae": "neg_mean_absolute_error",
|
||||
"neg_rmse": "neg_root_mean_squared_error",
|
||||
"r2": "r2",
|
||||
}
|
||||
cv = KFold(n_splits=N_CV_FOLDS, shuffle=True, random_state=42)
|
||||
|
||||
results = cross_validate(
|
||||
model, X, y, cv=cv, scoring=scoring, return_train_score=False
|
||||
)
|
||||
|
||||
mean_scores: dict[str, float] = {}
|
||||
for metric, values in results.items():
|
||||
if not metric.startswith("test_"):
|
||||
continue
|
||||
key = metric[len("test_"):]
|
||||
score = float(np.mean(values))
|
||||
# Convert negated metrics back to positive for readability
|
||||
if key.startswith("neg_"):
|
||||
key = key[len("neg_"):]
|
||||
score = -score
|
||||
mean_scores[key] = round(score, 4)
|
||||
|
||||
return mean_scores
|
||||
|
||||
def _save_model(self, model: Any, target: str) -> None:
|
||||
"""Persist a trained model with joblib."""
|
||||
path = self.models_dir / f"{target}_model.joblib"
|
||||
joblib.dump(model, path)
|
||||
logger.info("Model saved to %s", path)
|
||||
|
||||
def _save_feature_importances(self, model: Any, target: str) -> None:
|
||||
"""Save feature importances as a sorted JSON file."""
|
||||
if not hasattr(model, "feature_importances_"):
|
||||
logger.warning(
|
||||
"Model for '%s' has no feature_importances_ attribute; skipping.",
|
||||
target,
|
||||
)
|
||||
return
|
||||
|
||||
importances = dict(
|
||||
zip(self._feature_columns, model.feature_importances_.tolist())
|
||||
)
|
||||
sorted_importances = dict(
|
||||
sorted(importances.items(), key=lambda kv: kv[1], reverse=True)
|
||||
)
|
||||
|
||||
path = self.models_dir / f"{target}_feature_importances.json"
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
json.dump(sorted_importances, fh, indent=2)
|
||||
|
||||
logger.info("Feature importances saved to %s", path)
|
||||
top5 = list(sorted_importances.items())[:5]
|
||||
logger.debug("Top-5 features for %s: %s", target, top5)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
trainer = ModelTrainer()
|
||||
results = trainer.train_all()
|
||||
print("\nCross-validation results:")
|
||||
for target, scores in results.items():
|
||||
print(f" {target}: {scores}")
|
||||
Reference in new issue
Block a user