mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 07:16:15 +00:00
395 lines
13 KiB
Python
395 lines
13 KiB
Python
"""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 persists the evaluation report in SQLite.
|
||
|
||
Classification metrics: accuracy, precision, recall, F1 (macro), AUC.
|
||
Regression metrics: MAE, RMSE, R2.
|
||
"""
|
||
|
||
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
|
||
|
||
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"
|
||
|
||
# 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
|
||
----------
|
||
store:
|
||
SQLite store from which the feature dataset is loaded.
|
||
dataset_table:
|
||
SQLite table containing the feature dataset.
|
||
models_dir:
|
||
Directory containing the trained ``.joblib`` model files.
|
||
test_size:
|
||
Fraction of the dataset to use as the test set.
|
||
"""
|
||
|
||
def __init__(
|
||
self,
|
||
store: SQLiteStore | None = None,
|
||
dataset_table: str = HISTORICAL_FEATURED_TABLE,
|
||
models_dir: Path | str = MODELS_DIR,
|
||
test_size: float = TEST_SIZE,
|
||
) -> None:
|
||
self.store = store if store is not None else SQLiteStore()
|
||
self.dataset_table = dataset_table
|
||
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 the report to SQLite.
|
||
|
||
Returns
|
||
-------
|
||
dict
|
||
``{target_name: {metric_name: value, ...}}``
|
||
|
||
"""
|
||
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 latest feature importances written by
|
||
``ModelTrainer`` into SQLite, 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 no persisted feature importances exist for the requested target.
|
||
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())}"
|
||
)
|
||
|
||
importances = self.store.load_feature_importances(model_name)
|
||
if not importances:
|
||
raise FileNotFoundError(
|
||
f"Feature importances not found in SQLite for target: {model_name}. "
|
||
"Run train_model.py first."
|
||
)
|
||
return importances
|
||
|
||
# ------------------------------------------------------------------
|
||
# Private helpers
|
||
# ------------------------------------------------------------------
|
||
|
||
def _load_dataset(self) -> None:
|
||
"""Load the processed dataset and derive feature column names."""
|
||
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 pipeline first."
|
||
)
|
||
|
||
logger.info("Loading dataset from SQLite table %s", self.dataset_table)
|
||
|
||
non_feature_cols = set(TARGETS.keys()) | {
|
||
"date",
|
||
"station",
|
||
"station_id",
|
||
"open_status",
|
||
"snow_quality",
|
||
"season",
|
||
}
|
||
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 _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:
|
||
"""Persist the evaluation report to SQLite."""
|
||
run_id = self.store.save_evaluation_run(
|
||
dataset_table=self.dataset_table,
|
||
report=report,
|
||
models_dir=str(self.models_dir),
|
||
)
|
||
logger.info("Evaluation report saved to SQLite with id %d", run_id)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 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}")
|