feat(storage): migrate project to sqlite

This commit is contained in:
dasemu committed 2026-03-13 06:50:18 +01:00
1 parent 1bc1e58781
commit 9c8ba03574
17 files changed
+1204 -688

No files matched your search

+47 -37
View File
@@ -1,14 +1,13 @@
"""Evaluate trained ski-condition prediction models.
Loads each model from ml/models/, runs evaluation on a held-out test split
of the processed feature dataset, computes task-appropriate metrics, and
writes a JSON report to ml/models/evaluation_report.json.
Loads each model from ``ml/models/``, runs evaluation on a held-out test
split of the processed feature dataset, computes task-appropriate metrics,
and persists the evaluation report in SQLite.
Classification metrics: accuracy, precision, recall, F1 (macro), AUC.
Regression metrics: MAE, RMSE, R2.
"""
import json
import logging
from pathlib import Path
from typing import Any
@@ -28,15 +27,15 @@ from sklearn.metrics import (
from sklearn.model_selection import train_test_split
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"
REPORT_PATH = MODELS_DIR / "evaluation_report.json"
# Test split fraction. With a small dataset 20 % gives at least a handful of
# samples per class while keeping enough for stratification.
@@ -59,8 +58,10 @@ class ModelEvaluator:
Parameters
----------
dataset_path:
Path to the processed feature CSV.
store:
SQLite store from which the feature dataset is loaded.
dataset_table:
SQLite table containing the feature dataset.
models_dir:
Directory containing the trained ``.joblib`` model files.
test_size:
@@ -69,11 +70,13 @@ class ModelEvaluator:
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,
test_size: float = TEST_SIZE,
) -> 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.test_size = test_size
@@ -87,16 +90,13 @@ class ModelEvaluator:
# ------------------------------------------------------------------
def evaluate_all(self) -> dict[str, dict[str, float]]:
"""Evaluate all trained models and persist a JSON report.
"""Evaluate all trained models and persist the report to SQLite.
Returns
-------
dict
``{target_name: {metric_name: value, ...}}``
Side effects
------------
Writes ``ml/models/evaluation_report.json``.
"""
self._load_dataset()
self._load_models()
@@ -121,9 +121,8 @@ class ModelEvaluator:
def get_feature_importance(self, model_name: str) -> list[tuple[str, float]]:
"""Return feature importances for a trained model, sorted descending.
This method reads the pre-computed importance JSON written by
``ModelTrainer`` rather than recomputing from the model, so the
trainer must have been run first.
This method reads the latest feature importances written by
``ModelTrainer`` into SQLite, so the trainer must have been run first.
Parameters
----------
@@ -137,7 +136,7 @@ class ModelEvaluator:
Raises
------
FileNotFoundError
If the corresponding JSON importance file does not exist.
If no persisted feature importances exist for the requested target.
ValueError
If *model_name* is not a recognised target.
"""
@@ -147,18 +146,13 @@ class ModelEvaluator:
f"Valid names: {list(TARGETS.keys())}"
)
importance_path = self.models_dir / f"{model_name}_feature_importances.json"
if not importance_path.exists():
importances = self.store.load_feature_importances(model_name)
if not importances:
raise FileNotFoundError(
f"Feature importance file not found: {importance_path}. "
f"Feature importances not found in SQLite for target: {model_name}. "
"Run train_model.py first."
)
with open(importance_path, encoding="utf-8") as fh:
raw: dict[str, float] = json.load(fh)
sorted_importances = sorted(raw.items(), key=lambda kv: kv[1], reverse=True)
return sorted_importances
return importances
# ------------------------------------------------------------------
# Private helpers
@@ -166,16 +160,30 @@ class ModelEvaluator:
def _load_dataset(self) -> None:
"""Load the processed dataset and derive feature column names."""
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}. "
f"Processed dataset not found in SQLite table {self.dataset_table}. "
"Run the 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)
non_feature_cols = set(TARGETS.keys()) | {"date", "station"}
non_feature_cols = set(TARGETS.keys()) | {
"date",
"station",
"station_id",
"open_status",
"snow_quality",
"season",
}
string_cols = set(
self._df.select_dtypes(include=["object", "string"]).columns
)
non_feature_cols |= string_cols
self._feature_columns = [
col for col in self._df.columns if col not in non_feature_cols
]
@@ -332,11 +340,13 @@ class ModelEvaluator:
}
def _save_report(self, report: dict[str, Any]) -> None:
"""Write the evaluation report to disk as JSON."""
self.models_dir.mkdir(parents=True, exist_ok=True)
with open(REPORT_PATH, "w", encoding="utf-8") as fh:
json.dump(report, fh, indent=2)
logger.info("Evaluation report saved to %s", REPORT_PATH)
"""Persist the evaluation report to SQLite."""
run_id = self.store.save_evaluation_run(
dataset_table=self.dataset_table,
report=report,
models_dir=str(self.models_dir),
)
logger.info("Evaluation report saved to SQLite with id %d", run_id)
# ---------------------------------------------------------------------------
+32 -21
View File
@@ -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)