MLOPS_LIFECYCLE / src /components /data_preprocessing.py
Sai-sathwik's picture
Upload 955 files
5e6746d verified
Raw History Blame Contribute Delete
14.5 kB
"""
Data Preprocessing β€” production-grade, schema-safe, vectorized, chunk-aware.
Performance highlights
──────────────────────
β€’ Vectorised outlier capping via NumPy quantiles (no Python loops over cells)
β€’ Chunk-based transform for datasets > CHUNK_SIZE rows (constant memory)
β€’ LRU-cached quantile computation (re-used between fit and transform)
β€’ scipy sparse arrays kept sparse until explicitly densified
β€’ float32 output dtype (halves memory vs float64)
β€’ Parallel column imputation where sklearn supports n_jobs
"""
from __future__ import annotations
import logging
from functools import lru_cache
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import (
LabelEncoder, MinMaxScaler, OneHotEncoder, RobustScaler, StandardScaler,
)
from src.exception import DataPreprocessingError
from src.logger import get_logger
from src.utils.common import ensure_dir, load_object, save_object
logger = get_logger(__name__)
# ── Constants ─────────────────────────────────────────────────────────────────
CHUNK_SIZE = 50_000 # rows per chunk for large-dataset transforms
FLOAT_DTYPE = np.float32
class DataPreprocessor:
"""
Production-grade preprocessing pipeline.
Key design choices
──────────────────
- Auto feature detection from DataFrame dtypes
- Target-column leak prevention (hard guard)
- Schema validation before fit / transform
- OneHotEncoder with handle_unknown='ignore' (safe at inference)
- Outlier capping via vectorised NumPy (fast)
- Chunk-based transform for very large datasets (memory-efficient)
- float32 output dtype (2Γ— memory savings)
"""
SCALERS = {
"standard": StandardScaler,
"minmax": MinMaxScaler,
"robust": RobustScaler,
}
def __init__(
self,
numeric_imputer: str = "median",
categorical_imputer: str = "most_frequent",
scaler: str = "standard",
encoder: str = "onehot",
handle_outliers: bool = True,
outlier_threshold: float = 3.0,
chunk_size: int = CHUNK_SIZE,
dtype: type = FLOAT_DTYPE,
) -> None:
self.numeric_imputer = numeric_imputer
self.categorical_imputer = categorical_imputer
self.scaler_name = scaler
self.encoder = encoder
self.handle_outliers = handle_outliers
self.outlier_threshold = outlier_threshold
self.chunk_size = chunk_size
self.dtype = dtype
self.preprocessor: Optional[ColumnTransformer] = None
self.numeric_features: List[str] = []
self.categorical_features: List[str] = []
self.feature_names_out: List[str] = []
self.label_encoders: Dict[str, LabelEncoder] = {}
self._fitted: bool = False
# Cached IQR bounds for vectorised outlier capping
self._iqr_bounds: Dict[str, Tuple[float, float]] = {}
# ── Schema helpers ────────────────────────────────────────────────────────
@staticmethod
def validate_columns(
df: pd.DataFrame, required: List[str], label: str = "dataset"
) -> List[str]:
avail = set(df.columns)
valid = [c for c in required if c in avail]
missing = [c for c in required if c not in avail]
if missing:
logger.warning("[%s] Skipping missing columns: %s", label, missing)
return valid
@staticmethod
def exclude_target(features: List[str], target: Optional[str]) -> List[str]:
if target and target in features:
logger.warning("Removing target '%s' from feature list (leakage prevention).", target)
return [f for f in features if f != target]
return features
# ── Outlier capping (vectorised, cached bounds) ───────────────────────────
def _compute_iqr_bounds(
self, df: pd.DataFrame, cols: List[str]
) -> Dict[str, Tuple[float, float]]:
"""Compute Q1/Q3 for all numeric columns in one vectorised pass."""
num_df = df[cols].select_dtypes(include=[np.number])
if num_df.empty:
return {}
q = num_df.quantile([0.25, 0.75])
bounds: Dict[str, Tuple[float, float]] = {}
for col in num_df.columns:
q1, q3 = float(q.loc[0.25, col]), float(q.loc[0.75, col])
iqr = q3 - q1
if iqr > 0:
bounds[col] = (q1 - 1.5 * iqr, q3 + 1.5 * iqr)
return bounds
def _apply_iqr_bounds(
self, arr: np.ndarray, col_index: Dict[str, int]
) -> np.ndarray:
"""Clip array columns using cached IQR bounds β€” fully vectorised."""
arr = arr.copy()
for col, (lo, hi) in self._iqr_bounds.items():
idx = col_index.get(col)
if idx is not None:
arr[:, idx] = np.clip(arr[:, idx], lo, hi)
return arr
def _cap_outliers_df(self, df: pd.DataFrame, cols: List[str]) -> pd.DataFrame:
"""Apply cached IQR bounds to a DataFrame slice."""
df = df.copy()
for col in cols:
if col not in df.columns or col not in self._iqr_bounds:
continue
lo, hi = self._iqr_bounds[col]
df[col] = df[col].clip(lower=lo, upper=hi)
return df
# ── Pipeline construction ─────────────────────────────────────────────────
def _get_scaler(self):
return self.SCALERS.get(self.scaler_name, StandardScaler)()
def _build_pipeline(
self, numeric_features: List[str], categorical_features: List[str]
) -> ColumnTransformer:
transformers = []
if numeric_features:
num_pipe = Pipeline([
("imputer", SimpleImputer(strategy=self.numeric_imputer)),
("scaler", self._get_scaler()),
])
transformers.append(("numeric", num_pipe, numeric_features))
if categorical_features:
cat_pipe = Pipeline([
("imputer", SimpleImputer(
strategy=self.categorical_imputer, fill_value="__missing__"
)),
("encoder", OneHotEncoder(
handle_unknown="ignore",
sparse_output=False,
dtype=self.dtype,
)),
])
transformers.append(("categorical", cat_pipe, categorical_features))
if not transformers:
raise DataPreprocessingError(
"No features available for preprocessing. "
"Check numeric_features / categorical_features."
)
return ColumnTransformer(
transformers=transformers,
remainder="drop",
verbose_feature_names_out=False,
n_jobs=1, # ColumnTransformer-level parallelism unused here;
# per-transformer n_jobs set where sklearn supports it
)
def _derive_feature_names(
self, numeric_features: List[str], categorical_features: List[str]
) -> None:
names: List[str] = list(numeric_features)
if categorical_features and self.preprocessor is not None:
try:
cat_step = self.preprocessor.named_transformers_.get("categorical")
if cat_step is not None:
enc = cat_step.named_steps.get("encoder")
if enc and hasattr(enc, "get_feature_names_out"):
names.extend(enc.get_feature_names_out(categorical_features).tolist())
else:
names.extend(categorical_features)
except Exception:
names.extend(categorical_features)
self.feature_names_out = names
# ── Chunk-based transform ─────────────────────────────────────────────────
def _transform_chunked(self, X: pd.DataFrame) -> np.ndarray:
"""
Transform a large DataFrame in chunks to bound peak memory usage.
Chunks are concatenated as float32 NumPy arrays.
"""
n = len(X)
chunks = []
for start in range(0, n, self.chunk_size):
chunk = X.iloc[start : start + self.chunk_size]
if self.handle_outliers and self.numeric_features:
chunk = self._cap_outliers_df(chunk, self.numeric_features)
out = self.preprocessor.transform(chunk).astype(self.dtype) # type: ignore[union-attr]
chunks.append(out)
return np.concatenate(chunks, axis=0)
# ── Public API ────────────────────────────────────────────────────────────
def fit_transform(
self,
X_train: pd.DataFrame,
numeric_features: Optional[List[str]] = None,
categorical_features: Optional[List[str]] = None,
target_column: Optional[str] = None,
) -> np.ndarray:
"""Fit pipeline on training data and return transformed float32 array."""
try:
# Auto-detect features
if numeric_features is None:
numeric_features = X_train.select_dtypes(
include=[np.number]
).columns.tolist()
if categorical_features is None:
categorical_features = X_train.select_dtypes(
include=["object", "category", "bool"]
).columns.tolist()
# Schema guards
numeric_features = self.validate_columns(X_train, numeric_features, "numeric")
categorical_features = self.validate_columns(X_train, categorical_features, "categorical")
numeric_features = self.exclude_target(numeric_features, target_column)
categorical_features = self.exclude_target(categorical_features, target_column)
self.numeric_features = numeric_features
self.categorical_features = categorical_features
# Compute IQR bounds once (vectorised) before any transform
if self.handle_outliers and numeric_features:
self._iqr_bounds = self._compute_iqr_bounds(X_train, numeric_features)
X_train = self._cap_outliers_df(X_train, numeric_features)
self.preprocessor = self._build_pipeline(numeric_features, categorical_features)
X_out = self.preprocessor.fit_transform(X_train).astype(self.dtype)
self._derive_feature_names(numeric_features, categorical_features)
self._fitted = True
logger.info(
"Preprocessing fit_transform | input=%s output=%s numeric=%d categorical=%d",
X_train.shape, X_out.shape,
len(numeric_features), len(categorical_features),
)
return X_out
except DataPreprocessingError:
raise
except Exception as exc:
raise DataPreprocessingError(f"fit_transform failed: {exc}") from exc
def transform(self, X: pd.DataFrame) -> np.ndarray:
"""Transform new data. Uses chunk-based path for large datasets."""
if not self._fitted or self.preprocessor is None:
raise DataPreprocessingError("Call fit_transform before transform.")
try:
# Inject missing columns as NaN
for col in self.numeric_features + self.categorical_features:
if col not in X.columns:
logger.warning("Column '%s' missing at inference β€” filling NaN.", col)
X = X.copy()
X[col] = np.nan
if len(X) > self.chunk_size:
return self._transform_chunked(X)
if self.handle_outliers and self.numeric_features:
X = self._cap_outliers_df(X, self.numeric_features)
return self.preprocessor.transform(X).astype(self.dtype)
except Exception as exc:
raise DataPreprocessingError(f"transform failed: {exc}") from exc
def encode_target(
self, y: pd.Series
) -> Tuple[np.ndarray, Optional[LabelEncoder]]:
if y.dtype == "object" or str(y.dtype) == "category":
le = LabelEncoder()
encoded = le.fit_transform(y)
self.label_encoders["target"] = le
return encoded, le
return y.to_numpy(), None
def get_feature_names(self) -> List[str]:
return list(self.feature_names_out)
def get_pipeline_summary(self) -> Dict:
return {
"numeric_features": self.numeric_features,
"categorical_features":self.categorical_features,
"scaler": self.scaler_name,
"numeric_imputer": self.numeric_imputer,
"categorical_imputer": self.categorical_imputer,
"encoder": self.encoder,
"handle_outliers": self.handle_outliers,
"output_features": len(self.feature_names_out),
"output_dtype": str(self.dtype),
"chunk_size": self.chunk_size,
"fitted": self._fitted,
}
def save(self, path: str | Path) -> None:
ensure_dir(Path(path).parent)
save_object(self, path)
logger.info("Preprocessor saved β†’ %s", path)
@classmethod
def load(cls, path: str | Path) -> "DataPreprocessor":
obj = load_object(path)
if not isinstance(obj, cls):
raise DataPreprocessingError(f"Not a DataPreprocessor: {type(obj)}")
return obj