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)
# ---------------------------------------------------------------------------