Files
dasemu b5b62e582e fix(ml): resolve km_open under-prediction and remove Rule 3
- Removed data leakage features (lifts_open, snow_depth) from ML training.
- Added station_id as an encoded categorical feature to enable station-awareness.
- Removed Rule 3 (warm rain reduction) from the rules engine to avoid double-penalization.
- Retrained all models with the corrected feature set.
2026-03-13 10:01:43 +01:00

416 lines
14 KiB
Python

"""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)
Trained models are persisted under ``ml/models/`` via joblib. Structured
training metadata and feature importances are stored in SQLite.
Cross-validation (5-fold stratified for classifiers, KFold for regression)
is used throughout to compensate for the small dataset size.
"""
import logging
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
from storage import HISTORICAL_FEATURED_TABLE, SQLiteStore
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
_REPO_ROOT = Path(__file__).resolve().parents[1]
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
----------
store:
SQLite store from which the feature dataset is loaded.
dataset_table:
SQLite table containing the feature dataset.
models_dir:
Directory where trained models and importances are saved. Defaults to
``ml/models/`` relative to the repo root.
"""
def __init__(
self,
store: SQLiteStore | None = None,
dataset_table: str = HISTORICAL_FEATURED_TABLE,
models_dir: Path | str = MODELS_DIR,
sample_weight_min_ratio: float = 0.2,
) -> None:
self.store = store if store is not None else SQLiteStore()
self.dataset_table = dataset_table
self.models_dir = Path(models_dir)
self.models_dir.mkdir(parents=True, exist_ok=True)
self.sample_weight_min_ratio = sample_weight_min_ratio
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)
self.store.save_training_run(
dataset_table=self.dataset_table,
dataset_rows=len(self._df) if self._df is not None else 0,
metrics=cv_results,
models_dir=str(self.models_dir),
)
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, weights = 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, weights, model_type)
logger.info("CV scores for %s: %s", target, cv_scores)
# Final fit on the full available dataset
model.fit(X, y, sample_weight=weights)
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."""
self._df = self.store.read_dataframe(
self.dataset_table,
parse_dates=("date",),
)
if self._df.empty:
raise FileNotFoundError(
f"Processed dataset not found in SQLite table {self.dataset_table}. "
"Run the full dataset pipeline first."
)
logger.info("Loading dataset from SQLite table %s", self.dataset_table)
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 is handled separately as a categorical feature
"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",
# Data leakage: these are targets/status variables not in forecasts
"lifts_open",
"snow_depth",
}
# 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
]
# station_id will be added back as an encoded numeric feature
self._feature_columns.append("station_id")
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, np.ndarray]:
"""Return (X, y, weights) 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()
# Encode station_id
station_le = LabelEncoder()
X["station_id"] = station_le.fit_transform(X["station_id"].astype(str))
joblib.dump(station_le, self.models_dir / "station_id_label_encoder.joblib")
logger.debug("Encoded station_id using classes: %s", list(station_le.classes_))
X = X.fillna(X.median(numeric_only=True))
# Calculate sample weights based on date recency
weights = self._calculate_weights(df["date"])
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, weights
def _calculate_weights(self, dates: pd.Series) -> np.ndarray:
"""Assign linear weights where recent dates get 1.0 and oldest get min_ratio."""
dates_dt = pd.to_datetime(dates)
min_date = dates_dt.min()
max_date = dates_dt.max()
if max_date == min_date:
return np.ones(len(dates))
# Weight calculation: Linear decay
# w = min_ratio + (1 - min_ratio) * (date - min_date) / (max_date - min_date)
total_seconds = (max_date - min_date).total_seconds()
diff_seconds = (dates_dt - min_date).dt.total_seconds()
weights = self.sample_weight_min_ratio + (
1.0 - self.sample_weight_min_ratio
) * (diff_seconds / total_seconds)
return weights.values
def _cross_validate(
self,
model: Any,
X: pd.DataFrame,
y: pd.Series | np.ndarray,
weights: 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)
# In sklearn, cross_validate accepts fit_params or params (v1.4+)
# We pass sample_weight to ensure weights are respected during CV training
results = cross_validate(
model,
X,
y,
cv=cv,
scoring=scoring,
params={"sample_weight": weights},
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:
"""Persist feature importances for the latest trained model."""
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)
)
self.store.save_feature_importances(
target=target,
importances=sorted_importances,
)
logger.info("Feature importances saved to SQLite for %s", target)
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}")