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,7 @@
|
||||
"""ML package for ski predictor.
|
||||
|
||||
Modules:
|
||||
train_model: Trains RandomForest, GradientBoosting, and LightGBM models
|
||||
for station_open, km_open, and crowd_level targets.
|
||||
evaluate_model: Evaluates trained models and produces a JSON report.
|
||||
"""
|
||||
@@ -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}")
|
||||
@@ -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