Spaces:
Sleeping
Sleeping
File size: 1,921 Bytes
4df7cbe | 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 | """
Simplified feature engineering for planning-bucket classification.
Only 5 real features + 384 embedding dims = 389 total.
No city, no province, no day_of_month, no per-counterparty stats.
The merchant name embedding does the heavy lifting.
Usage:
from src.data.preprocessor_v2 import build_feature_matrix
feat_df = build_feature_matrix(raw_df)
"""
import re
import numpy as np
import pandas as pd
_STRIP_PATTERN = re.compile(r"[^a-z\s]")
def clean_merchant_name(name: str) -> str:
if not isinstance(name, str):
return ""
return " ".join(_STRIP_PATTERN.sub(" ", name.lower()).split())
def build_feature_matrix(df: pd.DataFrame, include_targets: bool = True) -> pd.DataFrame:
out = pd.DataFrame(index=df.index)
# Amount (log-compressed)
amount_cad = df["amount_minor"].abs() / 100.0
out["amount_log1p"] = np.log1p(amount_cad)
# Direction
out["is_inflow"] = (df["amount_minor"] < 0).astype(int)
# Income ratio
income = df.get("monthly_income_minor", pd.Series(0, index=df.index))
income = income.replace(0, np.nan).fillna(np.nan)
out["income_ratio"] = (df["amount_minor"].abs() / income).fillna(-1.0)
# Merchant name (cleaned, for embedding lookup)
out["merchant_name_clean"] = df["merchant_name"].apply(clean_merchant_name)
# Categorical
out["account_type"] = df.get("account_type", pd.Series("unknown", index=df.index)).fillna("unknown").astype(str)
out["is_recurring_candidate"] = df.get("is_recurring_candidate", pd.Series("unknown", index=df.index)).fillna("unknown").astype(str)
# Target
if include_targets and "planning_bucket" in df.columns:
out["planning_bucket"] = df["planning_bucket"]
return out
NUMERIC_FEATURES = ["amount_log1p", "is_inflow", "income_ratio"]
CATEGORICAL_FEATURES = ["account_type", "is_recurring_candidate"]
TABULAR_FEATURES = NUMERIC_FEATURES + CATEGORICAL_FEATURES
|