sales-forecasting-dashboard / src /forecasting_models.py
Hamza4100's picture
Upload 20 files
9349f93 verified
Raw History Blame Contribute Delete
3.14 kB
"""
forecasting_models.py
---------------------
Model registry and training utilities for the Sales Forecasting Dashboard.
"""
from __future__ import annotations
import copy
from typing import Dict, List, Optional
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import Ridge
# ---------------------------------------------------------------------------
# Model registry
# ---------------------------------------------------------------------------
MODELS_CONFIG: Dict[str, object] = {
"Ridge Regression": Ridge(alpha=1.0),
"Random Forest": RandomForestRegressor(
n_estimators=200,
max_depth=10,
random_state=42,
n_jobs=-1,
),
"HistGradientBoosting": HistGradientBoostingRegressor(
max_iter=200,
random_state=42,
),
}
"""Mapping of model display-name to an *unfitted* scikit-learn estimator.
Do **not** mutate this dict at runtime; call :func:`train_models` to obtain
fitted copies.
"""
# ---------------------------------------------------------------------------
# Training helpers
# ---------------------------------------------------------------------------
def train_models(
X_train,
y_train,
selected_models: Optional[List[str]] = None,
) -> Dict[str, object]:
"""Fit one or more models on the provided training data.
Parameters
----------
X_train : array-like of shape (n_samples, n_features)
Training feature matrix.
y_train : array-like of shape (n_samples,)
Training target values.
selected_models : list[str], optional
Subset of keys from :data:`MODELS_CONFIG` to train. When ``None``
(default) all registered models are trained.
Returns
-------
dict[str, estimator]
``{model_name: fitted_estimator}`` for each trained model.
Raises
------
ValueError
If any name in *selected_models* is not found in :data:`MODELS_CONFIG`.
"""
if selected_models is None:
names_to_train = list(MODELS_CONFIG.keys())
else:
unknown = [n for n in selected_models if n not in MODELS_CONFIG]
if unknown:
raise ValueError(
f"Unknown model(s): {unknown}. "
f"Available: {list(MODELS_CONFIG.keys())}"
)
names_to_train = selected_models
fitted: Dict[str, object] = {}
for name in names_to_train:
# Deep-copy to avoid mutating the shared registry instance
model = copy.deepcopy(MODELS_CONFIG[name])
model.fit(X_train, y_train)
fitted[name] = model
return fitted
def predict(model: object, X) -> np.ndarray:
"""Safe prediction wrapper for any scikit-learn compatible estimator.
Parameters
----------
model : fitted estimator
Any scikit-learn estimator with a ``predict`` method.
X : array-like of shape (n_samples, n_features)
Feature matrix to predict on.
Returns
-------
np.ndarray
Predicted values, shape ``(n_samples,)``.
"""
return np.asarray(model.predict(X), dtype=float)