""" evaluation.py ------------- Model evaluation and comparison utilities for the Sales Forecasting Dashboard. """ from __future__ import annotations from typing import Dict import numpy as np import pandas as pd from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score # --------------------------------------------------------------------------- # Individual model evaluation # --------------------------------------------------------------------------- def evaluate_model( model: object, X_test, y_test, ) -> Dict: """Evaluate a fitted model on a held-out test set. Parameters ---------- model : fitted scikit-learn estimator Must implement a ``predict`` method. X_test : array-like of shape (n_samples, n_features) Test feature matrix. y_test : array-like of shape (n_samples,) True target values. Returns ------- dict Keys: * ``mae`` - Mean Absolute Error * ``rmse`` - Root Mean Squared Error * ``r2`` - R-squared score * ``mape`` - Mean Absolute Percentage Error (% units, 0-100+) * ``predictions`` - np.ndarray of predicted values """ y_true = np.asarray(y_test, dtype=float) y_pred = np.asarray(model.predict(X_test), dtype=float) mae = float(mean_absolute_error(y_true, y_pred)) rmse = float(np.sqrt(mean_squared_error(y_true, y_pred))) r2 = float(r2_score(y_true, y_pred)) # MAPE: skip zero/near-zero actuals to avoid division-by-zero nonzero_mask = np.abs(y_true) > 1e-9 if nonzero_mask.sum() > 0: mape = float( np.mean(np.abs((y_true[nonzero_mask] - y_pred[nonzero_mask]) / y_true[nonzero_mask])) * 100 ) else: mape = float("nan") return { "mae": mae, "rmse": rmse, "r2": r2, "mape": mape, "predictions": y_pred, } # --------------------------------------------------------------------------- # Multi-model comparison # --------------------------------------------------------------------------- def compare_models( models_dict: Dict[str, object], X_test, y_test, ) -> pd.DataFrame: """Evaluate multiple fitted models and return a comparison table. Parameters ---------- models_dict : dict[str, estimator] ``{model_name: fitted_model}`` mapping (e.g. from :func:`~forecasting_models.train_models`). X_test : array-like Test feature matrix. y_test : array-like True target values. Returns ------- pd.DataFrame Columns: ``Model``, ``MAE``, ``RMSE``, ``R2``, ``MAPE``. Sorted by ``RMSE`` ascending (best model first). """ records = [] for name, model in models_dict.items(): metrics = evaluate_model(model, X_test, y_test) records.append( { "Model": name, "MAE": round(metrics["mae"], 4), "RMSE": round(metrics["rmse"], 4), "R2": round(metrics["r2"], 4), "MAPE": round(metrics["mape"], 4) if not np.isnan(metrics["mape"]) else float("nan"), } ) comparison_df = pd.DataFrame(records).sort_values("RMSE").reset_index(drop=True) return comparison_df # --------------------------------------------------------------------------- # Best model selection # --------------------------------------------------------------------------- def select_best_model(comparison_df: pd.DataFrame) -> str: """Return the name of the model with the lowest RMSE. Parameters ---------- comparison_df : pd.DataFrame Output of :func:`compare_models`. Returns ------- str Model name (from the ``Model`` column) with the smallest ``RMSE``. """ return str(comparison_df.loc[comparison_df["RMSE"].idxmin(), "Model"]) # --------------------------------------------------------------------------- # Qualitative grading # --------------------------------------------------------------------------- def get_model_grade(rmse: float, mean_sales: float) -> str: """Translate RMSE / mean-sales ratio to a qualitative grade. Parameters ---------- rmse : float Root Mean Squared Error of the model. mean_sales : float Mean of the actual sales values in the test set. Returns ------- str One of ``"Excellent"``, ``"Good"``, ``"Fair"``, or ``"Poor"``. """ if mean_sales == 0: return "Poor" ratio = rmse / abs(mean_sales) if ratio < 0.10: return "Excellent" if ratio < 0.20: return "Good" if ratio < 0.35: return "Fair" return "Poor"