Datasets:
File size: 29,014 Bytes
02412f8 | 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 | """Naive / statistical methods for the MacroLens unified API.
Five concrete classes, one per (model × subset of tasks):
Persistence T1 (N, horizon) -- last-close tile
HistoricalAnalogue T4 (N,) -- per-event-type train mean
LogSizeOLS T2, T5 (N,) -- log1p OLS on numerics
SectorMedian T3, T6 long-form -- per-(sector, field) train median
MetroMedian T7 (N, 3) -- per-(state, property_type) median
Every class:
* Inherits :class:`_JoblibSaveMixin` (state.joblib + manifest.json).
* Registers via :func:`register` so `ml.methods.<Name>` finds it.
* Receives ``task`` as a constructor arg; a ``ValueError`` is raised if
the requested task is not in :attr:`tasks`.
Hard rules (enforced by ``tests/test_layer_isolation.py``):
* Zero IO (no ``pd.read_parquet``, no file reads, no config imports).
* Zero ``meta`` consumption — methods take only ``X`` (and at fit time,
``y``).
* Zero canonical-indices imports / subsampling.
* Zero eval imports.
"""
from __future__ import annotations
import importlib.metadata
import logging
from typing import Any, ClassVar
import numpy as np
import pandas as pd
from ._config import (
HistoricalAnalogueConfig,
LogSizeOLSConfig,
MetroMedianConfig,
PersistenceConfig,
SectorMedianConfig,
)
from ._registry import register
from .base import Method, _JoblibSaveMixin
logger = logging.getLogger(__name__)
_PERSISTENCE_DEFAULT_CLOSE_IDX_LOGGED: bool = False
# ── Internal lib_versions helper ──────────────────────────────────────────
def _naive_lib_versions() -> dict[str, str]:
"""Versions of the three libs the naive family actually uses.
Overrides the broader default in :class:`Method` (which probes torch /
transformers / vllm too) -- those are not imported here and recording
them on a naive-method RunRecord would be misleading.
"""
out: dict[str, str] = {}
for pkg in ("numpy", "pandas", "scikit-learn"):
try:
out[pkg] = importlib.metadata.version(pkg)
except importlib.metadata.PackageNotFoundError:
pass
return out
# ── T1 — Persistence ──────────────────────────────────────────────────────
@register(
name="persistence",
family="naive",
tasks=frozenset({"T1"}),
config_class=PersistenceConfig,
)
class Persistence(_JoblibSaveMixin, Method):
"""Forecast the future close trajectory by tiling the last lookback close.
Predict shape: ``(N, horizon)``. The class emits a constant trajectory
per row equal to ``X[:, -1, close_feature_idx]`` tiled ``horizon``
times. This is the trivial-floor baseline; any real T1 method should
beat it.
Notes
-----
* ``X`` is a numpy ndarray ``(N, lookback, F)`` with no column names,
so the runner is responsible for passing the close-feature index
via ``PersistenceConfig.close_feature_idx`` (default ``0``).
* ``horizon`` is read from ``y.shape[1]`` at fit time and stored as
``self._horizon``; if ``config.horizon`` is set it overrides.
"""
name: ClassVar[str] = "persistence"
family: ClassVar[str] = "naive"
tasks: ClassVar[frozenset[str]] = frozenset({"T1"})
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: PersistenceConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"Persistence does not support task={task!r}; "
f"supported: {sorted(self.tasks)}"
)
self.task = task
self.config = config or PersistenceConfig(**kwargs)
if self.task == "T1" and self.config.close_feature_idx == 0:
# Information-only: the canonical loader puts close at idx 0 so the
# default is fine in practice. Emit once per process via logger so
# batch instantiation doesn't pollute stderr.
global _PERSISTENCE_DEFAULT_CLOSE_IDX_LOGGED
if not _PERSISTENCE_DEFAULT_CLOSE_IDX_LOGGED:
logger.info(
"Persistence(task='T1'): close_feature_idx defaults to 0; "
"the runner should resolve the actual close column index "
"from meta.attrs['feature_names'] and pass it via config."
)
_PERSISTENCE_DEFAULT_CLOSE_IDX_LOGGED = True
self._horizon: int | None = None
self._close_feature_idx: int = int(self.config.close_feature_idx)
@classmethod
def default_config(cls) -> PersistenceConfig:
return PersistenceConfig()
def fit(self, X: np.ndarray, y: np.ndarray, *, seed: int = 42) -> "Persistence":
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"Persistence.fit: expected X shape (N, lookback, F); got "
f"type={type(X).__name__} shape={getattr(X, 'shape', '?')}"
)
if not isinstance(y, np.ndarray) or y.ndim != 2:
raise ValueError(
f"Persistence.fit: expected y shape (N, horizon); got "
f"type={type(y).__name__} shape={getattr(y, 'shape', '?')}"
)
# Honour explicit override; otherwise read horizon from y.
self._horizon = (
int(self.config.horizon)
if self.config.horizon is not None
else int(y.shape[1])
)
if self._close_feature_idx >= X.shape[2]:
raise ValueError(
f"Persistence.fit: close_feature_idx={self._close_feature_idx} "
f"out of bounds for F={X.shape[2]}"
)
return self
def predict(self, X: np.ndarray) -> np.ndarray:
if self._horizon is None:
raise RuntimeError("Persistence: call .fit(X, y) before .predict().")
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"Persistence.predict: expected (N, lookback, F); got "
f"type={type(X).__name__} shape={getattr(X, 'shape', '?')}"
)
if self._close_feature_idx >= X.shape[2]:
raise ValueError(
f"Persistence.predict: close_feature_idx={self._close_feature_idx} "
f"out of bounds for F={X.shape[2]}"
)
last_close = X[:, -1, self._close_feature_idx][:, np.newaxis]
return np.tile(last_close, (1, self._horizon)).astype(np.float32)
def lib_versions(self) -> dict[str, str]:
return _naive_lib_versions()
# ── T4 — HistoricalAnalogue ───────────────────────────────────────────────
@register(
name="historical_analogue",
family="naive",
tasks=frozenset({"T4"}),
config_class=HistoricalAnalogueConfig,
)
class HistoricalAnalogue(_JoblibSaveMixin, Method):
"""Predict scenario return as the per-``event_type`` train mean.
``X`` is the T4 DataFrame ``[lookback, event_type, event_description]``;
only ``event_type`` is consumed. Unseen event types fall back to the
global train mean.
Predict shape: ``(N,)`` float32.
"""
name: ClassVar[str] = "historical_analogue"
family: ClassVar[str] = "naive"
tasks: ClassVar[frozenset[str]] = frozenset({"T4"})
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: HistoricalAnalogueConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"HistoricalAnalogue does not support task={task!r}; "
f"supported: {sorted(self.tasks)}"
)
self.task = task
self.config = config or HistoricalAnalogueConfig(**kwargs)
self._type_mean: dict[str, float] = {}
self._global_mean: float = 0.0
self._fitted: bool = False
@classmethod
def default_config(cls) -> HistoricalAnalogueConfig:
return HistoricalAnalogueConfig()
@staticmethod
def _event_types(X: pd.DataFrame) -> np.ndarray:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"HistoricalAnalogue: expected DataFrame X; got "
f"{type(X).__name__}"
)
if "event_type" not in X.columns:
raise ValueError(
"HistoricalAnalogue: X is missing 'event_type' column."
)
return np.asarray(X["event_type"].values, dtype=object).astype(str)
def fit(
self, X: pd.DataFrame, y: np.ndarray, *, seed: int = 42
) -> "HistoricalAnalogue":
et = self._event_types(X)
y_arr = np.asarray(y, dtype=np.float64).ravel()
if et.shape[0] != y_arr.shape[0]:
raise ValueError(
f"HistoricalAnalogue.fit: event_type/y length mismatch "
f"({et.shape[0]} vs {y_arr.shape[0]})"
)
df = pd.DataFrame({"event_type": et, "ret": y_arr}).dropna(subset=["ret"])
if df.empty:
raise RuntimeError("HistoricalAnalogue.fit: no usable training rows.")
self._type_mean = df.groupby("event_type")["ret"].mean().to_dict()
self._global_mean = float(df["ret"].mean())
self._fitted = True
return self
def predict(self, X: pd.DataFrame) -> np.ndarray:
if not self._fitted:
raise RuntimeError(
"HistoricalAnalogue: call .fit(X, y) before .predict()."
)
et = self._event_types(X)
return np.array(
[self._type_mean.get(e, self._global_mean) for e in et],
dtype=np.float32,
)
def lib_versions(self) -> dict[str, str]:
return _naive_lib_versions()
# ── T2 / T5 — LogSizeOLS ──────────────────────────────────────────────────
# LogSizeOLS removed from the registry per panel-design decision (replaced by
# RandomForest in classical.py). Class kept to preserve save/load
# compatibility for any old checkpoint, but no longer registered → not
# discovered by ``methods.ALL_METHODS`` and not runnable through the
# unified runner.
class LogSizeOLS(_JoblibSaveMixin, Method):
"""OLS regression of ``log1p(market_cap)`` on ``log1p(numeric features)``.
Classical-ML baseline (fitted parametric model): for T2 / T5 inputs,
fits a ``sklearn.linear_model.LinearRegression`` on
``log1p(numeric_columns)`` plus optional sector dummies, with target
``log1p(actual_market_cap)``. Predicts in log space and returns the
dollar-space prediction via ``np.expm1``.
Predict shape: ``(N,)`` float32.
"""
name: ClassVar[str] = "log_size_ols"
family: ClassVar[str] = "classical"
tasks: ClassVar[frozenset[str]] = frozenset({"T2", "T5"})
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: LogSizeOLSConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"LogSizeOLS does not support task={task!r}; "
f"supported: {sorted(self.tasks)}"
)
self.task = task
self.config = config or LogSizeOLSConfig(**kwargs)
self._model: Any = None
self._numeric_cols: list[str] = []
self._sector_dummy_cols: list[str] = []
self._train_columns: list[str] = [] # post-concat order
@classmethod
def default_config(cls) -> LogSizeOLSConfig:
return LogSizeOLSConfig()
@staticmethod
def _select_numeric(df: pd.DataFrame) -> list[str]:
"""Return the columns this method treats as size-proxy numerics.
Anything numeric that is neither a key (``ticker``/``date``) nor
the target itself qualifies. The exact set depends on the inputs
file the loader projected onto -- T5 strips price-derived
features upstream, so the same selector works for T2 and T5.
"""
skip = {"ticker", "date", "actual_market_cap", "derived_market_cap"}
return [
c
for c in df.columns
if c not in skip and pd.api.types.is_numeric_dtype(df[c])
]
def _build_features(
self, X: pd.DataFrame, *, train_columns: list[str] | None
) -> pd.DataFrame:
"""log1p of numerics + (optional) sector dummies, aligned to train.
``train_columns`` is None at fit time; the post-concat order is
captured for predict-time alignment.
"""
numeric_cols = (
self._numeric_cols if train_columns is not None else self._select_numeric(X)
)
num = X.reindex(columns=numeric_cols).apply(
lambda s: pd.to_numeric(s, errors="coerce").fillna(0.0)
)
# log1p; clip negative values to 0 to keep the log defined.
num = num.clip(lower=0.0)
num = np.log1p(num)
if self.config.sector_dummies and "sector" in X.columns:
dum = pd.get_dummies(X["sector"], prefix="sec", dtype=np.float32)
else:
dum = pd.DataFrame(index=X.index)
feat = pd.concat(
[num.reset_index(drop=True), dum.reset_index(drop=True)], axis=1
).fillna(0.0)
if train_columns is None:
# fit-time -- record the resolved numeric cols + dummy cols
self._numeric_cols = list(numeric_cols)
self._sector_dummy_cols = list(dum.columns)
self._train_columns = list(feat.columns)
return feat
# predict-time: align to train_columns (add missing as 0; drop extras)
for c in train_columns:
if c not in feat.columns:
feat[c] = 0.0
return feat[train_columns].fillna(0.0)
def fit(self, X: pd.DataFrame, y: np.ndarray, *, seed: int = 42) -> "LogSizeOLS":
from sklearn.linear_model import LinearRegression
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"LogSizeOLS.fit: expected DataFrame X; got {type(X).__name__}"
)
y_arr = np.asarray(y, dtype=np.float64).ravel()
if y_arr.shape[0] != len(X):
raise ValueError(
f"LogSizeOLS.fit: y length {y_arr.shape[0]} != "
f"X length {len(X)}"
)
# Drop rows with non-positive / NaN target (log1p needs >= 0).
mask = np.isfinite(y_arr) & (y_arr > 0)
if not mask.any():
raise RuntimeError(
"LogSizeOLS.fit: zero rows after dropping non-positive / NaN targets."
)
X_fit = X.loc[mask].reset_index(drop=True)
y_fit = y_arr[mask]
feat = self._build_features(X_fit, train_columns=None)
target = np.log1p(y_fit.astype(np.float64))
model = LinearRegression()
model.fit(feat.values, target)
self._model = model
return self
def predict(self, X: pd.DataFrame) -> np.ndarray:
if self._model is None:
raise RuntimeError("LogSizeOLS: call .fit(X, y) before .predict().")
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"LogSizeOLS.predict: expected DataFrame; got {type(X).__name__}"
)
feat = self._build_features(X, train_columns=self._train_columns)
pred_log = self._model.predict(feat.values)
# Clip in log space to avoid expm1 overflow.
pred_log = np.clip(pred_log, 0.0, 50.0)
return np.expm1(pred_log).astype(np.float32)
def lib_versions(self) -> dict[str, str]:
return _naive_lib_versions()
# ── T3 / T6 — SectorMedian ────────────────────────────────────────────────
@register(
name="sector_median",
family="naive",
tasks=frozenset({"T3", "T6"}),
config_class=SectorMedianConfig,
)
class SectorMedian(_JoblibSaveMixin, Method):
"""Predict each XBRL field as the per-(sector, field) train median.
At fit time the method:
1. Reads the set of fields to predict from ``y["field"].unique()``
(locked in :attr:`fitted_fields`).
2. Inner-joins ``y`` against ``X[ticker, fiscal_year, sector]`` to
attach the train sector per row.
3. Groups by ``(sector, field)`` -> median(value), with a per-field
global median fallback for unseen sectors.
Predict emits a long-form DataFrame with one row per
``(ticker, fiscal_year)`` × every fitted field, with the looked-up
sector median (fallback to per-field global median).
Predict columns: ``[ticker, fiscal_year, field, pred]``.
"""
name: ClassVar[str] = "sector_median"
family: ClassVar[str] = "naive"
tasks: ClassVar[frozenset[str]] = frozenset({"T3", "T6"})
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: SectorMedianConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"SectorMedian does not support task={task!r}; "
f"supported: {sorted(self.tasks)}"
)
self.task = task
self.config = config or SectorMedianConfig(**kwargs)
self.fitted_fields: list[str] = []
self._field_sector_median: dict[tuple[str, str], float] = {}
self._field_global_median: dict[str, float] = {}
@classmethod
def default_config(cls) -> SectorMedianConfig:
return SectorMedianConfig()
@staticmethod
def _check_xy(X: pd.DataFrame, y: pd.DataFrame) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"SectorMedian: expected DataFrame X; got {type(X).__name__}"
)
if not isinstance(y, pd.DataFrame):
raise TypeError(
f"SectorMedian: expected DataFrame y; got {type(y).__name__}"
)
for col in ("ticker", "fiscal_year"):
if col not in X.columns:
raise ValueError(f"SectorMedian: X missing '{col}'")
for col in ("ticker", "fiscal_year", "field", "value"):
if col not in y.columns:
raise ValueError(f"SectorMedian: y missing '{col}'")
def fit(
self, X: pd.DataFrame, y: pd.DataFrame, *, seed: int = 42
) -> "SectorMedian":
self._check_xy(X, y)
# Lock the set of fields to predict from y at fit time. The dataloader
# projects T3/T6 y onto a curated dense panel, so what's in y IS the
# full panel -- no need to extend with hardcoded defaults.
fitted_fields = sorted(y["field"].astype(str).unique())
if not fitted_fields:
raise RuntimeError("SectorMedian.fit: y has zero distinct 'field' values.")
self.fitted_fields = fitted_fields
# Build the (ticker, fiscal_year) -> sector lookup from X.
sec_col = "sector" if "sector" in X.columns else None
if sec_col is None:
# Without sector, we still fit but every row falls back to "Unknown".
x_keys = X[["ticker", "fiscal_year"]].copy()
x_keys["sector"] = "Unknown"
else:
x_keys = X[["ticker", "fiscal_year", "sector"]].copy()
x_keys["ticker"] = x_keys["ticker"].astype(str)
x_keys["fiscal_year"] = pd.to_numeric(
x_keys["fiscal_year"], errors="coerce"
).astype("Int64")
x_keys["sector"] = x_keys["sector"].astype(str).fillna("Unknown")
x_keys = x_keys.drop_duplicates(subset=["ticker", "fiscal_year"])
# Attach sector to y via inner join.
gt = y[["ticker", "fiscal_year", "field", "value"]].copy()
gt["ticker"] = gt["ticker"].astype(str)
gt["fiscal_year"] = pd.to_numeric(gt["fiscal_year"], errors="coerce").astype(
"Int64"
)
gt["field"] = gt["field"].astype(str)
gt["value_num"] = pd.to_numeric(gt["value"], errors="coerce")
joined = gt.merge(x_keys, on=["ticker", "fiscal_year"], how="left")
joined["sector"] = joined["sector"].fillna("Unknown")
valid = joined.dropna(subset=["value_num"])
if valid.empty:
raise RuntimeError(
"SectorMedian.fit: no rows with finite numeric values after coercion."
)
self._field_sector_median = (
valid.groupby(["field", "sector"])["value_num"].median().to_dict()
)
self._field_global_median = (
valid.groupby("field")["value_num"].median().to_dict()
)
return self
def predict(self, X: pd.DataFrame) -> pd.DataFrame:
if not self.fitted_fields:
raise RuntimeError("SectorMedian: call .fit(X, y) before .predict().")
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"SectorMedian.predict: expected DataFrame; got {type(X).__name__}"
)
for col in ("ticker", "fiscal_year"):
if col not in X.columns:
raise ValueError(f"SectorMedian.predict: X missing '{col}'")
keys = X[["ticker", "fiscal_year"]].copy()
if "sector" in X.columns:
keys["sector"] = X["sector"].astype(str).fillna("Unknown")
else:
keys["sector"] = "Unknown"
keys["ticker"] = keys["ticker"].astype(str)
keys["fiscal_year"] = pd.to_numeric(
keys["fiscal_year"], errors="coerce"
).astype("Int64")
rows: list[dict[str, Any]] = []
for ticker, fy, sector in zip(
keys["ticker"].values,
keys["fiscal_year"].values,
keys["sector"].values,
):
for fld in self.fitted_fields:
med = self._field_sector_median.get(
(fld, sector),
self._field_global_median.get(fld, 0.0),
)
rows.append(
{
"ticker": ticker,
"fiscal_year": fy,
"field": fld,
"pred": float(med) if pd.notna(med) else 0.0,
}
)
return pd.DataFrame(rows, columns=["ticker", "fiscal_year", "field", "pred"])
def lib_versions(self) -> dict[str, str]:
return _naive_lib_versions()
# Backward-compat alias for the legacy class name still referenced by
# methods/__init__.py (its registry-driven rewrite is the end-of-Phase-2
# deliverable; keeping the alias avoids breaking the package import in
# the meantime). Both names point at the same class.
LogSizeRegression = LogSizeOLS
# ── T7 — MetroMedian ──────────────────────────────────────────────────────
@register(
name="metro_median",
family="naive",
tasks=frozenset({"T7"}),
config_class=MetroMedianConfig,
)
class MetroMedian(_JoblibSaveMixin, Method):
"""Predict rent / price as per-(state, property_type) train medians.
Default metro key is ``state_property_type``; ``state`` and
``city_state`` are also supported via :attr:`MetroMedianConfig.metro_key`.
Fit consumes ``y[address, rent, price]`` for the train labels and
``X[state, property_type]`` for the metro key. Unseen metros fall back
to the global train median (per output).
Predict columns: ``[address, pred_rent, pred_price]``.
"""
name: ClassVar[str] = "metro_median"
family: ClassVar[str] = "naive"
tasks: ClassVar[frozenset[str]] = frozenset({"T7"})
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: MetroMedianConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"MetroMedian does not support task={task!r}; "
f"supported: {sorted(self.tasks)}"
)
self.task = task
self.config = config or MetroMedianConfig(**kwargs)
self._metro_rent_median: dict[str, float] = {}
self._metro_price_median: dict[str, float] = {}
self._global_rent_median: float = 0.0
self._global_price_median: float = 0.0
self._has_rent: bool = False
self._has_price: bool = False
self._fitted: bool = False
@classmethod
def default_config(cls) -> MetroMedianConfig:
return MetroMedianConfig()
def _metro_key(self, df: pd.DataFrame) -> np.ndarray:
"""Build the per-row metro key from X according to config.metro_key."""
kind = self.config.metro_key
if kind == "state":
cols = ["state"]
elif kind == "city_state":
cols = ["city", "state"]
elif kind == "state_property_type":
cols = ["state", "property_type"]
else: # pragma: no cover -- pydantic Literal forbids other values
raise ValueError(f"Unknown metro_key={kind!r}")
for c in cols:
if c not in df.columns:
raise ValueError(
f"MetroMedian: column '{c}' missing from X "
f"(metro_key={kind!r} requires {cols})"
)
parts = [df[c].astype(str).fillna("").str.strip() for c in cols]
out = parts[0]
for p in parts[1:]:
out = out.str.cat(p, sep="|")
return np.where(out.values == "", "Unknown", out.values)
def fit(
self, X: pd.DataFrame, y: pd.DataFrame, *, seed: int = 42
) -> "MetroMedian":
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"MetroMedian.fit: expected DataFrame X; got {type(X).__name__}"
)
if not isinstance(y, pd.DataFrame):
raise TypeError(
f"MetroMedian.fit: expected DataFrame y; got {type(y).__name__}"
)
# Align X and y on address (y is the canonical labels frame).
if "address" not in X.columns or "address" not in y.columns:
raise ValueError(
"MetroMedian.fit: both X and y must contain 'address'."
)
df = X.merge(
y[["address", *[c for c in ("rent", "price") if c in y.columns]]],
on="address",
how="inner",
)
if df.empty:
raise RuntimeError(
"MetroMedian.fit: zero rows after joining X with y on address."
)
metro = self._metro_key(df)
df = df.assign(_metro=metro)
if "rent" in df.columns:
rv = pd.to_numeric(df["rent"], errors="coerce")
r = pd.DataFrame({"metro": df["_metro"].values, "rent": rv.values}).dropna()
if not r.empty:
self._metro_rent_median = r.groupby("metro")["rent"].median().to_dict()
self._global_rent_median = float(r["rent"].median())
self._has_rent = True
if "price" in df.columns:
pv = pd.to_numeric(df["price"], errors="coerce")
p = pd.DataFrame({"metro": df["_metro"].values, "price": pv.values}).dropna()
if not p.empty:
self._metro_price_median = p.groupby("metro")["price"].median().to_dict()
self._global_price_median = float(p["price"].median())
self._has_price = True
self._fitted = True
return self
def predict(self, X: pd.DataFrame) -> pd.DataFrame:
if not self._fitted:
raise RuntimeError("MetroMedian: call .fit(X, y) before .predict().")
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"MetroMedian.predict: expected DataFrame; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("MetroMedian.predict: X missing 'address'.")
metro = self._metro_key(X)
out = pd.DataFrame({"address": X["address"].astype(str).values})
if self._has_rent:
out["pred_rent"] = [
self._metro_rent_median.get(m, self._global_rent_median) for m in metro
]
else:
out["pred_rent"] = np.nan
if self._has_price:
out["pred_price"] = [
self._metro_price_median.get(m, self._global_price_median) for m in metro
]
else:
out["pred_price"] = np.nan
return out
def lib_versions(self) -> dict[str, str]:
return _naive_lib_versions()
|