feature-pruning 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- feature_pruning/__init__.py +39 -0
- feature_pruning/core.py +486 -0
- feature_pruning-0.1.0.dist-info/METADATA +330 -0
- feature_pruning-0.1.0.dist-info/RECORD +7 -0
- feature_pruning-0.1.0.dist-info/WHEEL +5 -0
- feature_pruning-0.1.0.dist-info/licenses/LICENSE.txt +21 -0
- feature_pruning-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Feature Pruning: High-Performance Feature Reduction for Credit Risk Scorecards
|
|
3
|
+
=============================================================================
|
|
4
|
+
|
|
5
|
+
`feature_pruning` is an enterprise-grade, distributed feature reduction library
|
|
6
|
+
specifically optimized for developing regulatory-compliant credit risk scorecards
|
|
7
|
+
(such as Basel II/III, IFRS 9, and retail scorecard models).
|
|
8
|
+
|
|
9
|
+
Key Capabilities:
|
|
10
|
+
-----------------
|
|
11
|
+
- Automated variable classification (numeric, categorical, datetime, high-cardinality).
|
|
12
|
+
- Memory-efficient precision downcasting for massive distributed datasets.
|
|
13
|
+
- Fast distributed Information Value (IV) calculation via quantile binning.
|
|
14
|
+
- IV-prioritized Pearson correlation matrix pruning to eliminate multicollinearity.
|
|
15
|
+
- Transparent audit trail tracking all feature inclusion and exclusion decisions.
|
|
16
|
+
|
|
17
|
+
Quick Example:
|
|
18
|
+
--------------
|
|
19
|
+
>>> from feature_pruning import FeatureSelectionPipeline
|
|
20
|
+
>>> pipeline = FeatureSelectionPipeline(
|
|
21
|
+
... df=spark_df,
|
|
22
|
+
... target_col="default_flag",
|
|
23
|
+
... mandatory_features=["bureau_score", "annual_income"],
|
|
24
|
+
... exclude_features=["applicant_id"],
|
|
25
|
+
... iv_threshold=0.03,
|
|
26
|
+
... corr_threshold=0.95,
|
|
27
|
+
... )
|
|
28
|
+
>>> pruned_spark_df, audit_report = pipeline.run()
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from .core import FeatureSelectionPipeline
|
|
32
|
+
|
|
33
|
+
__version__ = "0.1.0"
|
|
34
|
+
__author__ = "Vrukshya"
|
|
35
|
+
__all__ = [
|
|
36
|
+
"FeatureSelectionPipeline",
|
|
37
|
+
"__version__",
|
|
38
|
+
"__author__",
|
|
39
|
+
]
|
feature_pruning/core.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import warnings
|
|
3
|
+
from typing import List, Tuple, Dict, Any, Optional
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import pyspark.sql.functions as F
|
|
9
|
+
from pyspark.sql import SparkSession, DataFrame as SparkDataFrame
|
|
10
|
+
from pyspark.sql.types import (
|
|
11
|
+
IntegerType, LongType, FloatType, DoubleType, DecimalType,
|
|
12
|
+
ByteType, ShortType, StringType, StructType, StructField,
|
|
13
|
+
)
|
|
14
|
+
from pyspark.storagelevel import StorageLevel
|
|
15
|
+
from pyspark.ml.stat import Correlation
|
|
16
|
+
from pyspark.ml.feature import VectorAssembler
|
|
17
|
+
|
|
18
|
+
warnings.filterwarnings("ignore")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FeatureSelectionPipeline:
|
|
22
|
+
"""End-to-end distributed feature reduction pipeline for credit risk scorecards.
|
|
23
|
+
|
|
24
|
+
This pipeline systematically filters high-dimensional feature spaces (e.g., thousands
|
|
25
|
+
of bureau, demographic, and transactional attributes) down to a curated, highly predictive,
|
|
26
|
+
and non-collinear feature set ready for Weight of Evidence (WoE) binning and Logistic
|
|
27
|
+
Regression scorecard modeling.
|
|
28
|
+
|
|
29
|
+
Execution Stages:
|
|
30
|
+
1. **step_identify_features**: Classifies columns into numeric, categorical,
|
|
31
|
+
datetime (auto-excluded), and high-cardinality (excluded if unique values > max_cat_levels).
|
|
32
|
+
2. **step_downcast**: Casts 64-bit numeric types (DecimalType, DoubleType) to FloatType
|
|
33
|
+
to reduce Spark cluster memory footprint and accelerate matrix computations.
|
|
34
|
+
3. **step_compute_iv**: Calculates Information Value (IV) across all candidates using
|
|
35
|
+
distributed quantile binning (`mapInPandas`). Features below `iv_threshold` are filtered out.
|
|
36
|
+
4. **step_prune_correlations**: Computes a Pearson correlation matrix via PySpark ML.
|
|
37
|
+
When two features have correlation >= `corr_threshold`, the feature with lower IV
|
|
38
|
+
is discarded to prevent multicollinearity.
|
|
39
|
+
5. **step_build_report**: Compiles a comprehensive audit DataFrame documenting the
|
|
40
|
+
status and exact exclusion reason for every input column.
|
|
41
|
+
|
|
42
|
+
Parameters:
|
|
43
|
+
df: Spark DataFrame containing candidate features and the binary target column.
|
|
44
|
+
target_col: Name of the binary target column (e.g., 'default_flag', 'bad_loan').
|
|
45
|
+
Must contain 0 (non-event / good) and 1 (event / bad).
|
|
46
|
+
mandatory_features: Optional list of column names that must never be dropped
|
|
47
|
+
regardless of IV or correlation (e.g., regulatory KPI ratios, bureau scores).
|
|
48
|
+
exclude_features: Optional list of column names to explicitly exclude from selection
|
|
49
|
+
(e.g., ID columns, leakage variables, date stamps).
|
|
50
|
+
iv_threshold: Minimum Information Value required to retain a feature.
|
|
51
|
+
Scorecard convention: < 0.02 (unpredictive), 0.02 - 0.1 (weak),
|
|
52
|
+
0.1 - 0.3 (medium), 0.3 - 0.5 (strong). Default is 0.03.
|
|
53
|
+
iv_n_bins: Number of quantile bins used for computing IV on continuous variables.
|
|
54
|
+
Default is 100.
|
|
55
|
+
iv_sample_rows: Maximum sample size used for computing distributed IV. Default is 1,000,000.
|
|
56
|
+
corr_threshold: Absolute Pearson correlation threshold above which collinear features
|
|
57
|
+
are pruned. Default is 0.95.
|
|
58
|
+
corr_sample_rows: Maximum sample size used for the correlation matrix calculation.
|
|
59
|
+
Default is 500,000.
|
|
60
|
+
max_corr_features: Maximum number of top IV features to feed into correlation pruning.
|
|
61
|
+
Default is 5000.
|
|
62
|
+
max_cat_levels: Maximum number of distinct categories permitted before a categorical
|
|
63
|
+
feature is flagged as high-cardinality and excluded. Default is 200.
|
|
64
|
+
expected_final_min: Minimum expected number of retained features. If correlation pruning
|
|
65
|
+
drops too many features, the threshold dynamically relaxes. Default is 200.
|
|
66
|
+
expected_final_max: Maximum cap on the final number of retained features. Default is 1000.
|
|
67
|
+
downcast: Whether to cast 64-bit floats/decimals to 32-bit float for memory efficiency.
|
|
68
|
+
Default is True.
|
|
69
|
+
verbose: Whether to log pipeline progress and execution times. Default is True.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
df: SparkDataFrame,
|
|
75
|
+
target_col: str,
|
|
76
|
+
mandatory_features: Optional[List[str]] = None,
|
|
77
|
+
exclude_features: Optional[List[str]] = None,
|
|
78
|
+
iv_threshold: float = 0.03,
|
|
79
|
+
iv_n_bins: int = 100,
|
|
80
|
+
iv_sample_rows: int = 1_000_000,
|
|
81
|
+
corr_threshold: float = 0.95,
|
|
82
|
+
corr_sample_rows: int = 500_000,
|
|
83
|
+
max_corr_features: int = 5000,
|
|
84
|
+
max_cat_levels: int = 200,
|
|
85
|
+
expected_final_min: int = 200,
|
|
86
|
+
expected_final_max: int = 1000,
|
|
87
|
+
downcast: bool = True,
|
|
88
|
+
verbose: bool = True,
|
|
89
|
+
):
|
|
90
|
+
self._log = print if verbose else (lambda *a, **k: None)
|
|
91
|
+
self.target_col = target_col.lower()
|
|
92
|
+
self.mandatory_features = [f.lower() for f in (mandatory_features or [])]
|
|
93
|
+
self.exclude_features = [f.lower() for f in (exclude_features or [])]
|
|
94
|
+
self.iv_threshold = iv_threshold
|
|
95
|
+
self.iv_n_bins = iv_n_bins
|
|
96
|
+
self.iv_sample_rows = iv_sample_rows
|
|
97
|
+
self.corr_threshold = corr_threshold
|
|
98
|
+
self.corr_sample_rows = corr_sample_rows
|
|
99
|
+
self.max_corr_features = max_corr_features
|
|
100
|
+
self.max_cat_levels = max_cat_levels
|
|
101
|
+
self.expected_final_min = expected_final_min
|
|
102
|
+
self.expected_final_max = expected_final_max
|
|
103
|
+
self.downcast_enabled = downcast
|
|
104
|
+
|
|
105
|
+
self.df_spark_ = df.toDF(*[c.lower() for c in df.columns])
|
|
106
|
+
self._spark = df.sparkSession
|
|
107
|
+
|
|
108
|
+
self.feature_types_ = None
|
|
109
|
+
self.iv_results_ = None
|
|
110
|
+
self.correlation_drops_ = None
|
|
111
|
+
self.final_features_ = None
|
|
112
|
+
self.feature_report_ = None
|
|
113
|
+
self.result_df_ = None
|
|
114
|
+
self._n_rows = None
|
|
115
|
+
self._direct_ok = None
|
|
116
|
+
self._df_work = None
|
|
117
|
+
|
|
118
|
+
def step_identify_features(self):
|
|
119
|
+
self._log("\n[Step 1/5] Identifying feature types...")
|
|
120
|
+
dtypes_str = dict(self.df_spark_.dtypes)
|
|
121
|
+
all_cols = [c for c in self.df_spark_.columns if c != self.target_col]
|
|
122
|
+
exclude_set = set(self.exclude_features)
|
|
123
|
+
mandatory_set = set(self.mandatory_features)
|
|
124
|
+
cat_type_names = {"string", "boolean"}
|
|
125
|
+
dt_type_names = {"date", "timestamp"}
|
|
126
|
+
|
|
127
|
+
numeric_cols, cat_candidates, datetime_cols = [], [], []
|
|
128
|
+
for c in all_cols:
|
|
129
|
+
if c in exclude_set:
|
|
130
|
+
continue
|
|
131
|
+
if dtypes_str[c] in dt_type_names:
|
|
132
|
+
datetime_cols.append(c)
|
|
133
|
+
elif dtypes_str[c] in cat_type_names:
|
|
134
|
+
cat_candidates.append(c)
|
|
135
|
+
else:
|
|
136
|
+
numeric_cols.append(c)
|
|
137
|
+
|
|
138
|
+
high_cardinality, keep_cat = [], []
|
|
139
|
+
if cat_candidates:
|
|
140
|
+
counts = self.df_spark_.agg(
|
|
141
|
+
*[F.approx_count_distinct(c).alias(c) for c in cat_candidates]
|
|
142
|
+
).first().asDict()
|
|
143
|
+
for c in cat_candidates:
|
|
144
|
+
if counts.get(c, 0) <= self.max_cat_levels or c in mandatory_set:
|
|
145
|
+
keep_cat.append(c)
|
|
146
|
+
else:
|
|
147
|
+
high_cardinality.append(c)
|
|
148
|
+
|
|
149
|
+
self.feature_types_ = {
|
|
150
|
+
"numeric": numeric_cols,
|
|
151
|
+
"categorical": keep_cat,
|
|
152
|
+
"datetime": datetime_cols,
|
|
153
|
+
"high_cardinality": high_cardinality,
|
|
154
|
+
}
|
|
155
|
+
self._log(
|
|
156
|
+
f" Numeric: {len(numeric_cols)} | Categorical: {len(keep_cat)} | "
|
|
157
|
+
f"Datetime(excl): {len(datetime_cols)} | High-card(excl): {len(high_cardinality)}"
|
|
158
|
+
)
|
|
159
|
+
return self
|
|
160
|
+
|
|
161
|
+
def step_downcast(self):
|
|
162
|
+
if not self.downcast_enabled:
|
|
163
|
+
self._log("\n[Step 2/5] Skipping downcast.")
|
|
164
|
+
return self
|
|
165
|
+
self._log("\n[Step 2/5] Downcasting to 32-bit...")
|
|
166
|
+
protected = set([self.target_col] + self.mandatory_features)
|
|
167
|
+
cast_map = []
|
|
168
|
+
for field in self.df_spark_.schema.fields:
|
|
169
|
+
name, dtype = field.name, field.dataType
|
|
170
|
+
if name in protected:
|
|
171
|
+
cast_map.append(
|
|
172
|
+
F.col(name).cast(DoubleType()).alias(name)
|
|
173
|
+
if isinstance(dtype, DecimalType)
|
|
174
|
+
else F.col(name)
|
|
175
|
+
)
|
|
176
|
+
elif isinstance(dtype, (DecimalType, DoubleType)):
|
|
177
|
+
cast_map.append(F.col(name).cast(FloatType()).alias(name))
|
|
178
|
+
else:
|
|
179
|
+
cast_map.append(F.col(name))
|
|
180
|
+
self.df_spark_ = self.df_spark_.select(*cast_map)
|
|
181
|
+
return self
|
|
182
|
+
|
|
183
|
+
def step_compute_iv(self):
|
|
184
|
+
if self.feature_types_ is None:
|
|
185
|
+
raise RuntimeError("Run step_identify_features() first.")
|
|
186
|
+
self._log(f"\n[Step 3/5] Computing Information Value ({self.iv_n_bins}-bin)...")
|
|
187
|
+
t0 = time.time()
|
|
188
|
+
|
|
189
|
+
numeric_cols = self.feature_types_["numeric"]
|
|
190
|
+
categorical_cols = self.feature_types_["categorical"]
|
|
191
|
+
select_cols = numeric_cols + categorical_cols + [self.target_col]
|
|
192
|
+
df_work = self.df_spark_.select(*select_cols).persist(StorageLevel.MEMORY_AND_DISK)
|
|
193
|
+
self._n_rows = df_work.count()
|
|
194
|
+
n_feat = len(numeric_cols) + len(categorical_cols)
|
|
195
|
+
self._log(f" Rows: {self._n_rows:,} | Features: {n_feat}")
|
|
196
|
+
|
|
197
|
+
self._direct_ok = (self._n_rows <= 500_000 and n_feat <= 200)
|
|
198
|
+
if self._direct_ok:
|
|
199
|
+
self._log(f" Small data - skipping IV, keeping ALL {n_feat} features.")
|
|
200
|
+
self.iv_results_ = pd.DataFrame({"feature": numeric_cols + categorical_cols, "iv": [None] * n_feat})
|
|
201
|
+
self._df_work = df_work
|
|
202
|
+
return self
|
|
203
|
+
|
|
204
|
+
iv_sdf = df_work.limit(self.iv_sample_rows) if self._n_rows > self.iv_sample_rows else df_work
|
|
205
|
+
iv_sdf = iv_sdf.filter(iv_sdf[self.target_col].isNotNull())
|
|
206
|
+
target_col = self.target_col
|
|
207
|
+
n_bins = self.iv_n_bins
|
|
208
|
+
|
|
209
|
+
totals = iv_sdf.agg(
|
|
210
|
+
F.count("*").alias("n"),
|
|
211
|
+
F.sum(F.col(target_col).cast("int")).alias("ev")
|
|
212
|
+
).collect()[0]
|
|
213
|
+
n_total, total_ev = totals["n"], int(totals["ev"])
|
|
214
|
+
total_non_ev = n_total - total_ev
|
|
215
|
+
if total_ev == 0 or total_non_ev == 0:
|
|
216
|
+
raise ValueError("Target has only one class.")
|
|
217
|
+
|
|
218
|
+
results = []
|
|
219
|
+
q_probs = np.array([i / n_bins for i in range(1, n_bins)])
|
|
220
|
+
|
|
221
|
+
if numeric_cols:
|
|
222
|
+
hist_schema = StructType([
|
|
223
|
+
StructField("feature", StringType(), False),
|
|
224
|
+
StructField("bin_id", IntegerType(), False),
|
|
225
|
+
StructField("cnt", LongType(), False),
|
|
226
|
+
StructField("events", LongType(), False),
|
|
227
|
+
])
|
|
228
|
+
n_cols_sel = len(numeric_cols) + 1
|
|
229
|
+
hist_parts = max(200, int(np.ceil(n_total * n_cols_sel * 4 / 25e6)))
|
|
230
|
+
|
|
231
|
+
sample_pdf = iv_sdf.select(*[F.col(c) for c in numeric_cols]).limit(50_000).toPandas()
|
|
232
|
+
bounds_map = {}
|
|
233
|
+
for c in numeric_cols:
|
|
234
|
+
vals = pd.to_numeric(sample_pdf[c], errors="coerce").dropna().to_numpy(dtype=np.float64)
|
|
235
|
+
if len(vals) < 10:
|
|
236
|
+
continue
|
|
237
|
+
bds = np.unique(np.quantile(vals, q_probs))
|
|
238
|
+
if len(bds) >= 1:
|
|
239
|
+
bounds_map[c] = bds
|
|
240
|
+
del sample_pdf
|
|
241
|
+
|
|
242
|
+
if bounds_map:
|
|
243
|
+
bounds_all = tuple(bounds_map.items())
|
|
244
|
+
empty_pdf = pd.DataFrame({
|
|
245
|
+
"feature": pd.Series(dtype="str"),
|
|
246
|
+
"bin_id": pd.Series(dtype="int32"),
|
|
247
|
+
"cnt": pd.Series(dtype="int64"),
|
|
248
|
+
"events": pd.Series(dtype="int64")
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
def _hist(pdf_iter, _b=bounds_all, _tc=target_col):
|
|
252
|
+
for pdf in pdf_iter:
|
|
253
|
+
tgt = pd.to_numeric(pdf[_tc], errors="coerce").fillna(0).astype(np.int64).to_numpy()
|
|
254
|
+
rows = []
|
|
255
|
+
for feat, bounds in _b:
|
|
256
|
+
if feat not in pdf.columns:
|
|
257
|
+
continue
|
|
258
|
+
vals = pd.to_numeric(pdf[feat], errors="coerce").to_numpy(dtype=np.float64, copy=False)
|
|
259
|
+
bins = np.searchsorted(bounds, np.nan_to_num(vals, nan=-np.inf), side="right").astype(np.int32)
|
|
260
|
+
cnt = np.bincount(bins, minlength=len(bounds) + 1)
|
|
261
|
+
ev = np.bincount(bins, weights=tgt, minlength=len(bounds) + 1)
|
|
262
|
+
for b in np.nonzero(cnt)[0].tolist():
|
|
263
|
+
rows.append((feat, int(b), int(cnt[b]), int(ev[b])))
|
|
264
|
+
yield pd.DataFrame(rows, columns=["feature", "bin_id", "cnt", "events"]) if rows else empty_pdf
|
|
265
|
+
|
|
266
|
+
agg_rows = (
|
|
267
|
+
iv_sdf.repartition(hist_parts)
|
|
268
|
+
.select([F.col(target_col).cast("int").alias(target_col)] + [F.col(c) for c in bounds_map])
|
|
269
|
+
.mapInPandas(_hist, schema=hist_schema)
|
|
270
|
+
.groupBy("feature", "bin_id")
|
|
271
|
+
.agg(F.sum("cnt").alias("cnt"), F.sum("events").alias("events"))
|
|
272
|
+
.collect()
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
feat_bins = defaultdict(list)
|
|
276
|
+
for row in agg_rows:
|
|
277
|
+
feat_bins[row["feature"]].append(row)
|
|
278
|
+
for feat, bins in feat_bins.items():
|
|
279
|
+
if len(bins) < 2:
|
|
280
|
+
continue
|
|
281
|
+
iv = 0.0
|
|
282
|
+
for row in bins:
|
|
283
|
+
ev_i, non_ev_i = int(row["events"]), int(row["cnt"]) - int(row["events"])
|
|
284
|
+
pct_ev = max(ev_i, 0.5) / total_ev
|
|
285
|
+
pct_non = max(non_ev_i, 0.5) / total_non_ev
|
|
286
|
+
iv += (pct_non - pct_ev) * np.log(pct_non / pct_ev)
|
|
287
|
+
results.append({"feature": feat, "iv": iv})
|
|
288
|
+
|
|
289
|
+
for feat in categorical_cols:
|
|
290
|
+
rows = iv_sdf.filter(F.col(feat).isNotNull()).groupBy(feat).agg(
|
|
291
|
+
F.count("*").alias("cnt"),
|
|
292
|
+
F.sum(F.col(target_col).cast("int")).alias("events")
|
|
293
|
+
).collect()
|
|
294
|
+
if len(rows) < 2:
|
|
295
|
+
continue
|
|
296
|
+
iv = 0.0
|
|
297
|
+
for row in rows:
|
|
298
|
+
ev_i, non_ev_i = int(row["events"]), int(row["cnt"]) - int(row["events"])
|
|
299
|
+
pct_ev = max(ev_i, 0.5) / total_ev
|
|
300
|
+
pct_non = max(non_ev_i, 0.5) / total_non_ev
|
|
301
|
+
iv += (pct_non - pct_ev) * np.log(pct_non / pct_ev)
|
|
302
|
+
results.append({"feature": feat, "iv": iv})
|
|
303
|
+
|
|
304
|
+
self.iv_results_ = pd.DataFrame(results).sort_values("iv", ascending=False).reset_index(drop=True) if results else pd.DataFrame(columns=["feature", "iv"])
|
|
305
|
+
self._df_work = df_work
|
|
306
|
+
n_pass = len(self.iv_results_[self.iv_results_["iv"] >= self.iv_threshold]) if len(self.iv_results_) > 0 else 0
|
|
307
|
+
self._log(f" IV done in {time.time() - t0:.1f}s | Features with IV >= {self.iv_threshold}: {n_pass}")
|
|
308
|
+
return self
|
|
309
|
+
|
|
310
|
+
def step_prune_correlations(self):
|
|
311
|
+
if self.iv_results_ is None:
|
|
312
|
+
self._log("\n[Step 4/5] Skipping correlation pruning - no IV results. Run step_compute_iv() first.")
|
|
313
|
+
self.correlation_drops_ = []
|
|
314
|
+
self.final_features_ = sorted(set(self.mandatory_features) - {""})
|
|
315
|
+
return self
|
|
316
|
+
self._log(f"\n[Step 4/5] Correlation pruning (threshold={self.corr_threshold})...")
|
|
317
|
+
t0 = time.time()
|
|
318
|
+
|
|
319
|
+
if self._direct_ok:
|
|
320
|
+
self._log(" Skipped (small data).")
|
|
321
|
+
all_feats = self.feature_types_["numeric"] + self.feature_types_["categorical"]
|
|
322
|
+
self.correlation_drops_ = []
|
|
323
|
+
self.final_features_ = sorted(set(all_feats + self.mandatory_features) - {""})
|
|
324
|
+
return self
|
|
325
|
+
|
|
326
|
+
numeric_set = set(self.feature_types_["numeric"])
|
|
327
|
+
iv_df = self.iv_results_
|
|
328
|
+
iv_passing = iv_df[iv_df["iv"] >= self.iv_threshold]["feature"].tolist()
|
|
329
|
+
top_numeric = [f for f in iv_passing if f in numeric_set and f not in self.mandatory_features]
|
|
330
|
+
top_categoric = [f for f in iv_passing if f not in numeric_set and f not in self.mandatory_features]
|
|
331
|
+
|
|
332
|
+
iv_order = iv_df.set_index("feature")
|
|
333
|
+
ordered_numeric = iv_order.loc[[f for f in top_numeric if f in iv_order.index]].sort_values("iv", ascending=False).index.tolist()
|
|
334
|
+
if self.max_corr_features and len(ordered_numeric) > self.max_corr_features:
|
|
335
|
+
ordered_numeric = ordered_numeric[:self.max_corr_features]
|
|
336
|
+
|
|
337
|
+
kept_numeric, dropped_info = [], []
|
|
338
|
+
if ordered_numeric:
|
|
339
|
+
corr_sdf = (self._df_work.limit(self.corr_sample_rows) if self._n_rows > self.corr_sample_rows else self._df_work)
|
|
340
|
+
sdf = corr_sdf.select(*ordered_numeric).fillna(0)
|
|
341
|
+
vec = VectorAssembler(inputCols=ordered_numeric, outputCol="features", handleInvalid="keep").transform(sdf).select("features")
|
|
342
|
+
corr_mat = Correlation.corr(vec, "features", "pearson").head()[0]
|
|
343
|
+
|
|
344
|
+
kept_idx = []
|
|
345
|
+
for i, f in enumerate(ordered_numeric):
|
|
346
|
+
drop = None
|
|
347
|
+
for j in kept_idx:
|
|
348
|
+
if abs(corr_mat[i, j]) >= self.corr_threshold:
|
|
349
|
+
drop = (ordered_numeric[j], abs(corr_mat[i, j]))
|
|
350
|
+
break
|
|
351
|
+
if drop:
|
|
352
|
+
dropped_info.append({"feature": f, "correlated_with": drop[0], "correlation_value": round(float(drop[1]), 4)})
|
|
353
|
+
else:
|
|
354
|
+
kept_numeric.append(f)
|
|
355
|
+
kept_idx.append(i)
|
|
356
|
+
|
|
357
|
+
if len(kept_numeric) < self.expected_final_min and self.corr_threshold < 0.98:
|
|
358
|
+
th2 = min(0.99, self.corr_threshold + 0.02)
|
|
359
|
+
self._log(f" Retrying with threshold={th2:.2f}")
|
|
360
|
+
kept_numeric, dropped_info, kept_idx = [], [], []
|
|
361
|
+
for i, f in enumerate(ordered_numeric):
|
|
362
|
+
drop = None
|
|
363
|
+
for j in kept_idx:
|
|
364
|
+
if abs(corr_mat[i, j]) >= th2:
|
|
365
|
+
drop = (ordered_numeric[j], abs(corr_mat[i, j]))
|
|
366
|
+
break
|
|
367
|
+
if drop:
|
|
368
|
+
dropped_info.append({"feature": f, "correlated_with": drop[0], "correlation_value": round(float(drop[1]), 4)})
|
|
369
|
+
else:
|
|
370
|
+
kept_numeric.append(f)
|
|
371
|
+
kept_idx.append(i)
|
|
372
|
+
|
|
373
|
+
if len(kept_numeric) > self.expected_final_max:
|
|
374
|
+
kept_numeric = kept_numeric[:self.expected_final_max]
|
|
375
|
+
|
|
376
|
+
self.correlation_drops_ = dropped_info
|
|
377
|
+
final_set = set(kept_numeric + top_categoric + self.mandatory_features)
|
|
378
|
+
final_set.discard("")
|
|
379
|
+
self.final_features_ = sorted(final_set)
|
|
380
|
+
self._log(f" Done in {time.time() - t0:.1f}s | Kept: {len(kept_numeric)} numeric + {len(top_categoric)} cat | Dropped: {len(dropped_info)}")
|
|
381
|
+
self._log(f" Final features: {len(self.final_features_)}")
|
|
382
|
+
return self
|
|
383
|
+
|
|
384
|
+
def step_build_report(self):
|
|
385
|
+
if self.final_features_ is None:
|
|
386
|
+
raise RuntimeError("Run step_prune_correlations() first.")
|
|
387
|
+
self._log("\n[Step 5/5] Building report & selecting columns...")
|
|
388
|
+
|
|
389
|
+
numeric_set = set(self.feature_types_["numeric"])
|
|
390
|
+
iv_lookup = dict(zip(self.iv_results_["feature"], self.iv_results_["iv"])) if len(self.iv_results_) > 0 else {}
|
|
391
|
+
corr_lookup = {d["feature"]: d for d in (self.correlation_drops_ or [])}
|
|
392
|
+
final_set = set(self.final_features_)
|
|
393
|
+
rows = []
|
|
394
|
+
|
|
395
|
+
for c in self.feature_types_["datetime"]:
|
|
396
|
+
rows.append({
|
|
397
|
+
"feature": c,
|
|
398
|
+
"dtype": "datetime",
|
|
399
|
+
"iv": None,
|
|
400
|
+
"correlated_with": None,
|
|
401
|
+
"correlation_value": None,
|
|
402
|
+
"is_selected": False,
|
|
403
|
+
"exclusion_reason": "datetime_column"
|
|
404
|
+
})
|
|
405
|
+
for c in self.feature_types_["high_cardinality"]:
|
|
406
|
+
rows.append({
|
|
407
|
+
"feature": c,
|
|
408
|
+
"dtype": "categorical",
|
|
409
|
+
"iv": None,
|
|
410
|
+
"correlated_with": None,
|
|
411
|
+
"correlation_value": None,
|
|
412
|
+
"is_selected": False,
|
|
413
|
+
"exclusion_reason": f"high_cardinality (>{self.max_cat_levels})"
|
|
414
|
+
})
|
|
415
|
+
for c in self.exclude_features:
|
|
416
|
+
if c not in [r["feature"] for r in rows]:
|
|
417
|
+
rows.append({
|
|
418
|
+
"feature": c,
|
|
419
|
+
"dtype": "excluded",
|
|
420
|
+
"iv": None,
|
|
421
|
+
"correlated_with": None,
|
|
422
|
+
"correlation_value": None,
|
|
423
|
+
"is_selected": False,
|
|
424
|
+
"exclusion_reason": "user_excluded"
|
|
425
|
+
})
|
|
426
|
+
|
|
427
|
+
for c in self.feature_types_["numeric"] + self.feature_types_["categorical"]:
|
|
428
|
+
dtype_str = "numeric" if c in numeric_set else "categorical"
|
|
429
|
+
iv_val = iv_lookup.get(c)
|
|
430
|
+
corr_with, corr_val, is_sel = None, None, c in final_set
|
|
431
|
+
if c in self.mandatory_features:
|
|
432
|
+
reason = ""
|
|
433
|
+
is_sel = True
|
|
434
|
+
elif c in corr_lookup:
|
|
435
|
+
reason = f"correlated (r={corr_lookup[c]['correlation_value']:.3f})"
|
|
436
|
+
corr_with, corr_val = corr_lookup[c]["correlated_with"], corr_lookup[c]["correlation_value"]
|
|
437
|
+
elif iv_val is not None and iv_val < self.iv_threshold:
|
|
438
|
+
reason = f"low_iv ({iv_val:.4f})"
|
|
439
|
+
elif not is_sel:
|
|
440
|
+
reason = "not_selected"
|
|
441
|
+
else:
|
|
442
|
+
reason = ""
|
|
443
|
+
rows.append({
|
|
444
|
+
"feature": c,
|
|
445
|
+
"dtype": dtype_str,
|
|
446
|
+
"iv": round(float(iv_val), 6) if iv_val is not None else None,
|
|
447
|
+
"correlated_with": corr_with,
|
|
448
|
+
"correlation_value": corr_val,
|
|
449
|
+
"is_selected": is_sel,
|
|
450
|
+
"exclusion_reason": reason
|
|
451
|
+
})
|
|
452
|
+
|
|
453
|
+
self.feature_report_ = pd.DataFrame(rows).sort_values(
|
|
454
|
+
["is_selected", "iv"], ascending=[False, False]
|
|
455
|
+
).reset_index(drop=True)
|
|
456
|
+
|
|
457
|
+
existing = set(self._df_work.columns)
|
|
458
|
+
final_select = [c for c in self.final_features_ if c in existing] + [self.target_col]
|
|
459
|
+
self.result_df_ = self._df_work.select(*final_select)
|
|
460
|
+
try:
|
|
461
|
+
self._df_work.unpersist()
|
|
462
|
+
except Exception:
|
|
463
|
+
pass
|
|
464
|
+
return self
|
|
465
|
+
|
|
466
|
+
def run(self) -> Tuple[SparkDataFrame, pd.DataFrame]:
|
|
467
|
+
t0 = time.time()
|
|
468
|
+
self._log(f"\n{'='*60}\nFEATURE SELECTION PIPELINE\n{'='*60}")
|
|
469
|
+
self.step_identify_features()
|
|
470
|
+
self.step_downcast()
|
|
471
|
+
self.step_compute_iv()
|
|
472
|
+
self.step_prune_correlations()
|
|
473
|
+
self.step_build_report()
|
|
474
|
+
self._log(f"\n{'='*60}\nDONE in {time.time() - t0:.1f}s | {len(self.final_features_)} features\n{'='*60}\n")
|
|
475
|
+
return self.result_df_, self.feature_report_
|
|
476
|
+
|
|
477
|
+
def get_selected_columns(self) -> List[str]:
|
|
478
|
+
return self.feature_report_[self.feature_report_["is_selected"]]["feature"].tolist()
|
|
479
|
+
|
|
480
|
+
def get_iv_summary(self) -> pd.DataFrame:
|
|
481
|
+
return self.iv_results_[self.iv_results_["iv"].notna()].sort_values("iv", ascending=False).reset_index(drop=True)
|
|
482
|
+
|
|
483
|
+
def get_correlation_drops(self) -> pd.DataFrame:
|
|
484
|
+
if not self.correlation_drops_:
|
|
485
|
+
return pd.DataFrame(columns=["feature", "correlated_with", "correlation_value"])
|
|
486
|
+
return pd.DataFrame(self.correlation_drops_).sort_values("correlation_value", ascending=False).reset_index(drop=True)
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: feature_pruning
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: High-performance PySpark library for scalable feature reduction and Information Value (IV) pruning in Credit Risk Scorecards
|
|
5
|
+
Author-email: Vrukshya <vrukshyaai@gmail.com>
|
|
6
|
+
Maintainer-email: Vrukshya <vrukshyaai@gmail.com>
|
|
7
|
+
License: MIT License
|
|
8
|
+
|
|
9
|
+
Copyright (c) 2026 Vrukshya Org
|
|
10
|
+
|
|
11
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
12
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
13
|
+
in the Software without restriction, including without limitation the rights
|
|
14
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
15
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
16
|
+
furnished to do so, subject to the following conditions:
|
|
17
|
+
|
|
18
|
+
The above copyright notice and this permission notice shall be included in all
|
|
19
|
+
copies or substantial portions of the Software.
|
|
20
|
+
|
|
21
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
22
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
23
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
24
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
25
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
26
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
27
|
+
SOFTWARE.
|
|
28
|
+
Project-URL: Homepage, https://github.com/vrukshya/feature_pruning
|
|
29
|
+
Project-URL: Documentation, https://github.com/vrukshya/feature_pruning#readme
|
|
30
|
+
Project-URL: Repository, https://github.com/vrukshya/feature_pruning
|
|
31
|
+
Project-URL: Bug Tracker, https://github.com/vrukshya/feature_pruning/issues
|
|
32
|
+
Keywords: credit-risk,credit-scoring,scorecard,feature-reduction,feature-pruning,feature-selection,information-value,woe,pyspark,fintech,machine-learning
|
|
33
|
+
Classifier: Development Status :: 4 - Beta
|
|
34
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
35
|
+
Classifier: Intended Audience :: Science/Research
|
|
36
|
+
Classifier: Intended Audience :: Developers
|
|
37
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
38
|
+
Classifier: Operating System :: OS Independent
|
|
39
|
+
Classifier: Programming Language :: Python :: 3
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
43
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
44
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
45
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
46
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
47
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
48
|
+
Requires-Python: >=3.8
|
|
49
|
+
Description-Content-Type: text/markdown
|
|
50
|
+
License-File: LICENSE.txt
|
|
51
|
+
Requires-Dist: numpy>=1.20.0
|
|
52
|
+
Requires-Dist: pandas>=1.3.0
|
|
53
|
+
Requires-Dist: pyspark>=3.1.0
|
|
54
|
+
Provides-Extra: dev
|
|
55
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
56
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
57
|
+
Requires-Dist: black>=23.0.0; extra == "dev"
|
|
58
|
+
Requires-Dist: flake8>=6.0.0; extra == "dev"
|
|
59
|
+
Requires-Dist: mypy>=1.0.0; extra == "dev"
|
|
60
|
+
Dynamic: license-file
|
|
61
|
+
|
|
62
|
+
# feature_pruning
|
|
63
|
+
|
|
64
|
+
[](https://pypi.org/project/feature-pruning/)
|
|
65
|
+
[](https://spark.apache.org/)
|
|
66
|
+
[](https://opensource.org/licenses/MIT)
|
|
67
|
+
[](https://github.com/psf/black)
|
|
68
|
+
|
|
69
|
+
**High-Performance Distributed Feature Reduction Engine for Credit Risk Scorecards.**
|
|
70
|
+
|
|
71
|
+
`feature_pruning` is an enterprise-grade Python library built natively on Apache Spark for selecting and pruning variables in credit risk scorecard development (Probability of Default / Basel II/III / IFRS 9 / Retail Scorecards).
|
|
72
|
+
|
|
73
|
+
It automates the transition from thousands of raw credit bureau, transaction, and demographic attributes down to an optimal, highly predictive, non-collinear feature set ready for Weight of Evidence (WoE) binning and Logistic Regression.
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## The Credit Risk Scorecard Challenge
|
|
78
|
+
|
|
79
|
+
Building regulatory-compliant credit scorecards presents unique data engineering and modeling hurdles:
|
|
80
|
+
|
|
81
|
+
- **Audit & Governance (SR 11-7 / Basel / IFRS 9)**: Model risk management (MRM) and regulatory auditors require an explicit justification for every discarded or retained variable.
|
|
82
|
+
- **Extreme Multicollinearity**: Credit bureau tables often contain dozens of collinear metrics (e.g., `num_inquiries_3m`, `num_inquiries_6m`, `num_inquiries_12m`). In standard logistic regression scorecards, collinearity causes unstable coefficients and counter-intuitive sign reversals.
|
|
83
|
+
- **Predictive Quality**: Features must meet minimum **Information Value (IV)** standards while preserving mandatory business or regulatory key indicators.
|
|
84
|
+
- **Big Data Scale**: Modern credit datasets often span millions of accounts and thousands of features. Single-machine libraries (pandas/scikit-learn) crash with `OutOfMemory` errors when computing quantile cuts and pairwise correlations.
|
|
85
|
+
|
|
86
|
+
`feature_pruning` solves these challenges by running distributed quantile binning, IV evaluation, and correlation pruning entirely within **Apache Spark**.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Pipeline Architecture
|
|
91
|
+
|
|
92
|
+
```
|
|
93
|
+
Raw Spark DataFrame (Millions of Rows, 1000s of Features)
|
|
94
|
+
│
|
|
95
|
+
▼
|
|
96
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
97
|
+
│ Stage 1: Feature Classification │
|
|
98
|
+
│ • Detects Numeric vs. Categorical vs. Datetime columns │
|
|
99
|
+
│ • Flags & filters high-cardinality strings (> max_cat_levels) │
|
|
100
|
+
│ • Protects mandatory features and excludes requested columns │
|
|
101
|
+
└──────────────────────────────────────────────────┬─────────────────────────────────────────────────────┘
|
|
102
|
+
│
|
|
103
|
+
▼
|
|
104
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
105
|
+
│ Stage 2: Distributed Precision Downcasting │
|
|
106
|
+
│ • Downcasts DoubleType & DecimalType to 32-bit FloatType │
|
|
107
|
+
│ • Cuts executor memory consumption by ~50% during matrix aggregation │
|
|
108
|
+
└──────────────────────────────────────────────────┬─────────────────────────────────────────────────────┘
|
|
109
|
+
│
|
|
110
|
+
▼
|
|
111
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
112
|
+
│ Stage 3: High-Throughput Information Value (IV) Computation │
|
|
113
|
+
│ • Computes continuous quantiles and distributed binning via Spark mapInPandas │
|
|
114
|
+
│ • Aggregates Goods/Bads and calculates IV for numeric and categorical variables │
|
|
115
|
+
│ • Filters out variables with IV < iv_threshold │
|
|
116
|
+
└──────────────────────────────────────────────────┬─────────────────────────────────────────────────────┘
|
|
117
|
+
│
|
|
118
|
+
▼
|
|
119
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
120
|
+
│ Stage 4: IV-Prioritized Correlation Pruning │
|
|
121
|
+
│ • Computes Pearson correlation matrix via PySpark VectorAssembler + Correlation │
|
|
122
|
+
│ • Between collinear pairs (r >= corr_threshold), retains the feature with higher IV │
|
|
123
|
+
│ • Dynamic threshold relaxation ensures minimum required feature count is met │
|
|
124
|
+
└──────────────────────────────────────────────────┬─────────────────────────────────────────────────────┘
|
|
125
|
+
│
|
|
126
|
+
▼
|
|
127
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
128
|
+
│ Stage 5: Full Audit Reporting & Data Delivery │
|
|
129
|
+
│ • Generates comprehensive audit DataFrame (is_selected, iv, correlated_with, exclusion_reason) │
|
|
130
|
+
│ • Outputs pruned Spark DataFrame ready for Weight of Evidence (WoE) binning │
|
|
131
|
+
└────────────────────────────────────────────────────────────────────────────────────────────────────────┘
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## Key Features
|
|
137
|
+
|
|
138
|
+
- ⚡ **Native PySpark Scalability**: Distributed quantile histograms and correlation matrices executed directly on cluster workers via Spark ML and `mapInPandas`.
|
|
139
|
+
- 📊 **IV-Driven Pruning**: When two features are collinear, the pipeline drops the weaker predictor and retains the variable with higher Information Value.
|
|
140
|
+
- 🛡️ **Mandatory Variable Protection**: Ensure business-critical variables (e.g., debt-to-income, credit bureau score) are never removed, regardless of their statistical properties.
|
|
141
|
+
- 📋 **Regulatory Audit Trail**: Automatically produces a full governance table explaining why every single column was accepted or eliminated (e.g., `low_iv (0.012)`, `correlated (r=0.962)`, `high_cardinality (>200)`, or `datetime_column`).
|
|
142
|
+
- 🔄 **Dynamic Threshold Relaxation**: Automatically adjusts correlation thresholds if filtering becomes overly aggressive, keeping feature counts within target bounds (`expected_final_min`, `expected_final_max`).
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
## Installation
|
|
147
|
+
|
|
148
|
+
### From PyPI
|
|
149
|
+
```bash
|
|
150
|
+
pip install feature-pruning
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### For Local Development
|
|
154
|
+
```bash
|
|
155
|
+
git clone https://github.com/vrukshya/feature_pruning.git
|
|
156
|
+
cd feature_pruning
|
|
157
|
+
pip install -e ".[dev]"
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### In Databricks / Cloud Notebooks
|
|
161
|
+
In your Databricks notebook cell:
|
|
162
|
+
```python
|
|
163
|
+
%pip install feature-pruning
|
|
164
|
+
```
|
|
165
|
+
Or add `feature-pruning` to your Databricks cluster libraries.
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## Quickstart
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from pyspark.sql import SparkSession
|
|
173
|
+
from feature_pruning import FeatureSelectionPipeline
|
|
174
|
+
|
|
175
|
+
# 1. Initialize Spark session (or use active session in Databricks/EMR)
|
|
176
|
+
spark = SparkSession.builder.appName("CreditRiskScorecard").getOrCreate()
|
|
177
|
+
|
|
178
|
+
# 2. Load credit training data
|
|
179
|
+
df = spark.table("risk_catalog.credit_data.application_train")
|
|
180
|
+
|
|
181
|
+
# 3. Configure the feature selection pipeline
|
|
182
|
+
pipeline = FeatureSelectionPipeline(
|
|
183
|
+
df=df,
|
|
184
|
+
target_col="default_flag", # 0 = Good loan, 1 = Default / Bad loan
|
|
185
|
+
mandatory_features=["bureau_score", "dti_ratio"], # Keep regardless of correlation
|
|
186
|
+
exclude_features=["application_id", "ssn_hash"], # Exclude identifiers
|
|
187
|
+
iv_threshold=0.03, # Industry baseline: IV >= 0.03
|
|
188
|
+
corr_threshold=0.95, # Multicollinearity cutoff
|
|
189
|
+
expected_final_min=20,
|
|
190
|
+
expected_final_max=150,
|
|
191
|
+
verbose=True,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# 4. Execute pipeline
|
|
195
|
+
selected_spark_df, audit_report = pipeline.run()
|
|
196
|
+
|
|
197
|
+
# 5. Review results
|
|
198
|
+
print("Selected features count:", len(pipeline.get_selected_columns()))
|
|
199
|
+
print("Selected columns:", pipeline.get_selected_columns())
|
|
200
|
+
|
|
201
|
+
# 6. Inspect audit report
|
|
202
|
+
print(audit_report.head(20))
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
## Inspection & Diagnostic Methods
|
|
208
|
+
|
|
209
|
+
After calling `pipeline.run()`, several diagnostic helpers allow inspection of the feature reduction decisions:
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
# 1. Retrieve list of final selected feature names
|
|
213
|
+
selected_features = pipeline.get_selected_columns()
|
|
214
|
+
|
|
215
|
+
# 2. Inspect Information Value ranking for all evaluated features
|
|
216
|
+
iv_summary = pipeline.get_iv_summary()
|
|
217
|
+
print(iv_summary.head(10))
|
|
218
|
+
|
|
219
|
+
# 3. Inspect which features were pruned due to correlation and their collinear counterpart
|
|
220
|
+
correlation_drops = pipeline.get_correlation_drops()
|
|
221
|
+
print(correlation_drops.head(10))
|
|
222
|
+
|
|
223
|
+
# 4. Full audit report with exact exclusion reasons
|
|
224
|
+
print(pipeline.feature_report_)
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
### Sample Audit Report Output
|
|
228
|
+
|
|
229
|
+
| feature | dtype | iv | correlated_with | correlation_value | is_selected | exclusion_reason |
|
|
230
|
+
|---|---|---|---|---|---|---|
|
|
231
|
+
| `bureau_score` | numeric | 0.4521 | None | None | True | |
|
|
232
|
+
| `utilization_rate`| numeric | 0.3180 | None | None | True | |
|
|
233
|
+
| `num_inquiries_6m` | numeric | 0.1420 | None | None | True | |
|
|
234
|
+
| `num_inquiries_3m` | numeric | 0.1210 | `num_inquiries_6m`| 0.965 | False | correlated (r=0.965) |
|
|
235
|
+
| `employer_name` | categorical | None | None | None | False | high_cardinality (>200) |
|
|
236
|
+
| `postal_code_raw`| numeric | 0.0120 | None | None | False | low_iv (0.0120) |
|
|
237
|
+
| `application_date`| datetime | None | None | None | False | datetime_column |
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## API Reference
|
|
242
|
+
|
|
243
|
+
### `FeatureSelectionPipeline`
|
|
244
|
+
|
|
245
|
+
```python
|
|
246
|
+
FeatureSelectionPipeline(
|
|
247
|
+
df: SparkDataFrame,
|
|
248
|
+
target_col: str,
|
|
249
|
+
mandatory_features: Optional[List[str]] = None,
|
|
250
|
+
exclude_features: Optional[List[str]] = None,
|
|
251
|
+
iv_threshold: float = 0.03,
|
|
252
|
+
iv_n_bins: int = 100,
|
|
253
|
+
iv_sample_rows: int = 1_000_000,
|
|
254
|
+
corr_threshold: float = 0.95,
|
|
255
|
+
corr_sample_rows: int = 500_000,
|
|
256
|
+
max_corr_features: int = 5000,
|
|
257
|
+
max_cat_levels: int = 200,
|
|
258
|
+
expected_final_min: int = 200,
|
|
259
|
+
expected_final_max: int = 1000,
|
|
260
|
+
downcast: bool = True,
|
|
261
|
+
verbose: bool = True,
|
|
262
|
+
)
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
| Parameter | Type | Default | Description |
|
|
266
|
+
|---|---|---|---|
|
|
267
|
+
| `df` | `SparkDataFrame` | *Required* | Input Spark DataFrame containing raw candidate variables and target. |
|
|
268
|
+
| `target_col` | `str` | *Required* | Name of the binary target (0 = Good, 1 = Bad). Case-insensitive. |
|
|
269
|
+
| `mandatory_features` | `List[str]` | `None` | Columns guaranteed to be retained regardless of IV or correlation. |
|
|
270
|
+
| `exclude_features` | `List[str]` | `None` | Columns explicitly excluded from candidate pool (IDs, timestamps). |
|
|
271
|
+
| `iv_threshold` | `float` | `0.03` | Minimum Information Value (IV) required for feature inclusion. |
|
|
272
|
+
| `iv_n_bins` | `int` | `100` | Quantile bin resolution for continuous variable histogram computation. |
|
|
273
|
+
| `iv_sample_rows` | `int` | `1,000,000` | Sample ceiling for computing quantile thresholds on continuous columns. |
|
|
274
|
+
| `corr_threshold` | `float` | `0.95` | Pearson correlation ceiling. Collinear variable with lower IV is pruned. |
|
|
275
|
+
| `corr_sample_rows` | `int` | `500,000` | Sample ceiling for Pearson correlation matrix calculation. |
|
|
276
|
+
| `max_corr_features` | `int` | `5000` | Upper limit of top IV features fed into correlation assembler. |
|
|
277
|
+
| `max_cat_levels` | `int` | `200` | Maximum unique levels allowed before categorical is dropped as high-cardinality. |
|
|
278
|
+
| `expected_final_min` | `int` | `200` | Minimum retained count. Relaxes `corr_threshold` if pruned too aggressively. |
|
|
279
|
+
| `expected_final_max` | `int` | `1000` | Maximum cap on final retained variables. |
|
|
280
|
+
| `downcast` | `bool` | `True` | Downcasts Decimal/Double columns to Float32 to optimize Spark worker memory. |
|
|
281
|
+
| `verbose` | `bool` | `True` | Prints stage progress and execution timing logs. |
|
|
282
|
+
|
|
283
|
+
---
|
|
284
|
+
|
|
285
|
+
## Credit Risk Scorecard Rules of Thumb
|
|
286
|
+
|
|
287
|
+
### Information Value (IV) Benchmarks
|
|
288
|
+
|
|
289
|
+
In credit risk modeling (Siddiqi, 2005), Information Value serves as the primary metric for filtering out uninformative signals:
|
|
290
|
+
|
|
291
|
+
| Information Value (IV) | Predictive Power | Action in Scorecard Development |
|
|
292
|
+
|---|---|---|
|
|
293
|
+
| **< 0.02** | Unpredictive | **Drop**: Adds noise and degrees of freedom without signal. |
|
|
294
|
+
| **0.02 – 0.10** | Weak Predictor | **Evaluate**: May be retained if part of a key credit policy dimension. |
|
|
295
|
+
| **0.10 – 0.30** | Medium Predictor | **Keep**: Core candidate for scorecard inclusion. |
|
|
296
|
+
| **0.30 – 0.50** | Strong Predictor | **Keep**: High diagnostic quality feature. |
|
|
297
|
+
| **> 0.50** | Suspicious / Too Good | **Investigate**: Often indicative of target leakage or operational bias. |
|
|
298
|
+
|
|
299
|
+
### Correlation Thresholds
|
|
300
|
+
|
|
301
|
+
- Standard practice sets the correlation threshold between `0.80` and `0.95`.
|
|
302
|
+
- Setting `corr_threshold=0.95` catches near-duplicate metrics (e.g., balance in dollars vs. balance in thousands).
|
|
303
|
+
- Setting `corr_threshold=0.85` produces a tighter, more orthogonal set of features that prevents variance inflation in final logistic regression models.
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## Performance & Spark Optimization
|
|
308
|
+
|
|
309
|
+
- **Quantile Binning (`mapInPandas`)**: Rather than running expensive full-dataset sorting on each column, `feature_pruning` samples continuous variables to establish robust quantile boundaries, then computes distributed frequency histograms across partitions in a single pass.
|
|
310
|
+
- **Spark Storage Management**: Intermediate working DataFrames are cached at `StorageLevel.MEMORY_AND_DISK` and unpersisted automatically at the conclusion of report generation.
|
|
311
|
+
- **Vector Correlation**: Correlation is calculated using Spark ML's native distributed linear algebra (`Correlation.corr`), supporting thousands of features simultaneously.
|
|
312
|
+
|
|
313
|
+
---
|
|
314
|
+
|
|
315
|
+
## Contributing
|
|
316
|
+
|
|
317
|
+
Contributions, bug reports, and feature requests are welcome!
|
|
318
|
+
Please feel free to submit a pull request or open an issue on GitHub.
|
|
319
|
+
|
|
320
|
+
1. Fork the Project
|
|
321
|
+
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
|
|
322
|
+
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
|
|
323
|
+
4. Push to the Branch (`git push origin feature/AmazingFeature`)
|
|
324
|
+
5. Open a Pull Request
|
|
325
|
+
|
|
326
|
+
---
|
|
327
|
+
|
|
328
|
+
## License
|
|
329
|
+
|
|
330
|
+
Distributed under the MIT License. See [LICENSE.txt](LICENSE.txt) for more details.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
feature_pruning/__init__.py,sha256=u3GiIQIRMSJVV-Q2mHSx193C68XJBwPViioxwFHlqlY,1407
|
|
2
|
+
feature_pruning/core.py,sha256=SbTNSoyBvXV0y78_fN74rYntD7XxgpD-3yjqd_4k8FM,23851
|
|
3
|
+
feature_pruning-0.1.0.dist-info/licenses/LICENSE.txt,sha256=Ifzkhdu7jmu8cJ7gJ9kb3HPfz2ZTSwJ6B6BUhJAXjm4,1088
|
|
4
|
+
feature_pruning-0.1.0.dist-info/METADATA,sha256=NzEQJbUyS6E8rgDRSHYJy2PRglu_hCD1Uy1L0hfaDqU,20280
|
|
5
|
+
feature_pruning-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
6
|
+
feature_pruning-0.1.0.dist-info/top_level.txt,sha256=mC52rgCaN2tZ8Nmrgb9cfNYSRWXfzFPC_CrWcmoQQ_w,16
|
|
7
|
+
feature_pruning-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vrukshya Org
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
feature_pruning
|