mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 23:36:17 +00:00
feat(storage): migrate project to sqlite
This commit is contained in:
1 parent
1bc1e58781
commit
9c8ba03574
17 files changed
+1204
-688
No files matched your search
+32
-21
@@ -5,14 +5,13 @@ Trains three models against the processed feature dataset:
|
||||
- km_open: regression (GradientBoostingRegressor)
|
||||
- crowd_level: multi-class classification (LGBMClassifier)
|
||||
|
||||
Models and feature importances are persisted under ml/models/ via joblib.
|
||||
Trained models are persisted under ``ml/models/`` via joblib. Structured
|
||||
training metadata and feature importances are stored in SQLite.
|
||||
Cross-validation (5-fold stratified for classifiers, KFold for regression)
|
||||
is used throughout to compensate for the small dataset size.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -24,13 +23,14 @@ from sklearn.ensemble import GradientBoostingRegressor, RandomForestClassifier
|
||||
from sklearn.model_selection import KFold, StratifiedKFold, cross_validate
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
|
||||
from storage import HISTORICAL_FEATURED_TABLE, SQLiteStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paths
|
||||
# ---------------------------------------------------------------------------
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
DATASET_PATH = _REPO_ROOT / "data" / "processed" / "dataset_featured.csv"
|
||||
MODELS_DIR = _REPO_ROOT / "ml" / "models"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -87,9 +87,10 @@ class ModelTrainer:
|
||||
|
||||
Parameters
|
||||
----------
|
||||
dataset_path:
|
||||
Path to the processed feature CSV. Defaults to
|
||||
``data/processed/dataset_featured.csv`` relative to the repo root.
|
||||
store:
|
||||
SQLite store from which the feature dataset is loaded.
|
||||
dataset_table:
|
||||
SQLite table containing the feature dataset.
|
||||
models_dir:
|
||||
Directory where trained models and importances are saved. Defaults to
|
||||
``ml/models/`` relative to the repo root.
|
||||
@@ -97,10 +98,12 @@ class ModelTrainer:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dataset_path: Path | str = DATASET_PATH,
|
||||
store: SQLiteStore | None = None,
|
||||
dataset_table: str = HISTORICAL_FEATURED_TABLE,
|
||||
models_dir: Path | str = MODELS_DIR,
|
||||
) -> None:
|
||||
self.dataset_path = Path(dataset_path)
|
||||
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)
|
||||
|
||||
@@ -127,6 +130,12 @@ class ModelTrainer:
|
||||
logger.info("Training model for target: %s", target)
|
||||
cv_results[target] = self.train_model(target, task_type)
|
||||
|
||||
self.store.save_training_run(
|
||||
dataset_table=self.dataset_table,
|
||||
dataset_rows=len(self._df) if self._df is not None else 0,
|
||||
metrics=cv_results,
|
||||
models_dir=str(self.models_dir),
|
||||
)
|
||||
logger.info("All models trained successfully.")
|
||||
return cv_results
|
||||
|
||||
@@ -191,14 +200,17 @@ class ModelTrainer:
|
||||
|
||||
def _load_dataset(self) -> None:
|
||||
"""Load the processed dataset from disk and derive feature columns."""
|
||||
if not self.dataset_path.exists():
|
||||
self._df = self.store.read_dataframe(
|
||||
self.dataset_table,
|
||||
parse_dates=("date",),
|
||||
)
|
||||
if self._df.empty:
|
||||
raise FileNotFoundError(
|
||||
f"Processed dataset not found at {self.dataset_path}. "
|
||||
"Run the pipeline first."
|
||||
f"Processed dataset not found in SQLite table {self.dataset_table}. "
|
||||
"Run the full dataset pipeline first."
|
||||
)
|
||||
|
||||
logger.info("Loading dataset from %s", self.dataset_path)
|
||||
self._df = pd.read_csv(self.dataset_path, parse_dates=["date"])
|
||||
logger.info("Loading dataset from SQLite table %s", self.dataset_table)
|
||||
|
||||
target_cols = set(MODEL_REGISTRY.keys())
|
||||
# Exclude date, station identifiers, target aliases, and non-numeric
|
||||
@@ -316,7 +328,7 @@ class ModelTrainer:
|
||||
logger.info("Model saved to %s", path)
|
||||
|
||||
def _save_feature_importances(self, model: Any, target: str) -> None:
|
||||
"""Save feature importances as a sorted JSON file."""
|
||||
"""Persist feature importances for the latest trained model."""
|
||||
if not hasattr(model, "feature_importances_"):
|
||||
logger.warning(
|
||||
"Model for '%s' has no feature_importances_ attribute; skipping.",
|
||||
@@ -330,12 +342,11 @@ class ModelTrainer:
|
||||
sorted_importances = dict(
|
||||
sorted(importances.items(), key=lambda kv: kv[1], reverse=True)
|
||||
)
|
||||
|
||||
path = self.models_dir / f"{target}_feature_importances.json"
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
json.dump(sorted_importances, fh, indent=2)
|
||||
|
||||
logger.info("Feature importances saved to %s", path)
|
||||
self.store.save_feature_importances(
|
||||
target=target,
|
||||
importances=sorted_importances,
|
||||
)
|
||||
logger.info("Feature importances saved to SQLite for %s", target)
|
||||
top5 = list(sorted_importances.items())[:5]
|
||||
logger.debug("Top-5 features for %s: %s", target, top5)
|
||||
|
||||
|
||||
Reference in new issue
Block a user