From 4daa73303999115c18556095e9d0287f6adb352e Mon Sep 17 00:00:00 2001 From: Dasemu Date: Fri, 13 Mar 2026 09:35:47 +0100 Subject: [PATCH] feat(ml): implement sample weighting by date recency Prioritize recent historical data to account for potential changes in data collection methodology at Infonieve over the years. Implemented linear weight decay from 1.0 (newest) to 0.2 (oldest). --- ml/train_model.py | 50 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/ml/train_model.py b/ml/train_model.py index f4bfda4..9834a57 100644 --- a/ml/train_model.py +++ b/ml/train_model.py @@ -101,11 +101,13 @@ class ModelTrainer: store: SQLiteStore | None = None, dataset_table: str = HISTORICAL_FEATURED_TABLE, models_dir: Path | str = MODELS_DIR, + sample_weight_min_ratio: float = 0.2, ) -> None: self.store = store if store is not None else SQLiteStore() self.dataset_table = dataset_table self.models_dir = Path(models_dir) self.models_dir.mkdir(parents=True, exist_ok=True) + self.sample_weight_min_ratio = sample_weight_min_ratio self._df: pd.DataFrame | None = None self._feature_columns: list[str] = [] @@ -148,7 +150,7 @@ class ModelTrainer: Column name of the prediction target (``station_open``, ``km_open``, or ``crowd_level``). model_type: - One of ``"binary"``, ``"multiclass"``, or ``"regression"``. + One of ``"binary"``, ``"multiclass", or ``"regression"``. Returns ------- @@ -178,15 +180,15 @@ class ModelTrainer: f"Unknown model_type '{model_type}'. Valid: {valid_types}" ) - X, y = self._prepare_features_and_target(target) + X, y, weights = 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) + cv_scores = self._cross_validate(model, X, y, weights, model_type) logger.info("CV scores for %s: %s", target, cv_scores) # Final fit on the full available dataset - model.fit(X, y) + model.fit(X, y, sample_weight=weights) logger.info("Final fit complete for target: %s", target) self._save_model(model, target) @@ -243,8 +245,8 @@ class ModelTrainer: 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.""" + ) -> tuple[pd.DataFrame, pd.Series | np.ndarray, np.ndarray]: + """Return (X, y, weights) with rows that have a valid target value.""" assert self._df is not None # guaranteed by callers df = self._df.dropna(subset=[target]).copy() @@ -256,6 +258,9 @@ class ModelTrainer: X = df[self._feature_columns].copy() X = X.fillna(X.median(numeric_only=True)) + # Calculate sample weights based on date recency + weights = self._calculate_weights(df["date"]) + if target == "crowd_level": # Encode string labels to integers in a stable order le = LabelEncoder() @@ -268,13 +273,34 @@ class ModelTrainer: else: y = df[target].values - return X, y + return X, y, weights + + def _calculate_weights(self, dates: pd.Series) -> np.ndarray: + """Assign linear weights where recent dates get 1.0 and oldest get min_ratio.""" + dates_dt = pd.to_datetime(dates) + min_date = dates_dt.min() + max_date = dates_dt.max() + + if max_date == min_date: + return np.ones(len(dates)) + + # Weight calculation: Linear decay + # w = min_ratio + (1 - min_ratio) * (date - min_date) / (max_date - min_date) + total_seconds = (max_date - min_date).total_seconds() + diff_seconds = (dates_dt - min_date).dt.total_seconds() + + weights = self.sample_weight_min_ratio + ( + 1.0 - self.sample_weight_min_ratio + ) * (diff_seconds / total_seconds) + + return weights.values def _cross_validate( self, model: Any, X: pd.DataFrame, y: pd.Series | np.ndarray, + weights: np.ndarray, model_type: str, ) -> dict[str, float]: """Run k-fold cross-validation and return mean scores. @@ -303,8 +329,16 @@ class ModelTrainer: } cv = KFold(n_splits=N_CV_FOLDS, shuffle=True, random_state=42) + # In sklearn, cross_validate accepts fit_params or params (v1.4+) + # We pass sample_weight to ensure weights are respected during CV training results = cross_validate( - model, X, y, cv=cv, scoring=scoring, return_train_score=False + model, + X, + y, + cv=cv, + scoring=scoring, + params={"sample_weight": weights}, + return_train_score=False, ) mean_scores: dict[str, float] = {}