File size: 3,144 Bytes
9349f93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""
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)