File size: 14,533 Bytes
5e6746d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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