feature-pruning 0.1.0__tar.gz
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-0.1.0/LICENSE.txt +21 -0
- feature_pruning-0.1.0/PKG-INFO +330 -0
- feature_pruning-0.1.0/README.md +269 -0
- feature_pruning-0.1.0/feature_pruning/__init__.py +39 -0
- feature_pruning-0.1.0/feature_pruning/core.py +486 -0
- feature_pruning-0.1.0/feature_pruning.egg-info/PKG-INFO +330 -0
- feature_pruning-0.1.0/feature_pruning.egg-info/SOURCES.txt +11 -0
- feature_pruning-0.1.0/feature_pruning.egg-info/dependency_links.txt +1 -0
- feature_pruning-0.1.0/feature_pruning.egg-info/requires.txt +10 -0
- feature_pruning-0.1.0/feature_pruning.egg-info/top_level.txt +1 -0
- feature_pruning-0.1.0/pyproject.toml +81 -0
- feature_pruning-0.1.0/setup.cfg +4 -0
- feature_pruning-0.1.0/tests/test_init.py +42 -0
|
@@ -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,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,269 @@
|
|
|
1
|
+
# feature_pruning
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/feature-pruning/)
|
|
4
|
+
[](https://spark.apache.org/)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
[](https://github.com/psf/black)
|
|
7
|
+
|
|
8
|
+
**High-Performance Distributed Feature Reduction Engine for Credit Risk Scorecards.**
|
|
9
|
+
|
|
10
|
+
`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).
|
|
11
|
+
|
|
12
|
+
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.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## The Credit Risk Scorecard Challenge
|
|
17
|
+
|
|
18
|
+
Building regulatory-compliant credit scorecards presents unique data engineering and modeling hurdles:
|
|
19
|
+
|
|
20
|
+
- **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.
|
|
21
|
+
- **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.
|
|
22
|
+
- **Predictive Quality**: Features must meet minimum **Information Value (IV)** standards while preserving mandatory business or regulatory key indicators.
|
|
23
|
+
- **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.
|
|
24
|
+
|
|
25
|
+
`feature_pruning` solves these challenges by running distributed quantile binning, IV evaluation, and correlation pruning entirely within **Apache Spark**.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Pipeline Architecture
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
Raw Spark DataFrame (Millions of Rows, 1000s of Features)
|
|
33
|
+
│
|
|
34
|
+
▼
|
|
35
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
36
|
+
│ Stage 1: Feature Classification │
|
|
37
|
+
│ • Detects Numeric vs. Categorical vs. Datetime columns │
|
|
38
|
+
│ • Flags & filters high-cardinality strings (> max_cat_levels) │
|
|
39
|
+
│ • Protects mandatory features and excludes requested columns │
|
|
40
|
+
└──────────────────────────────────────────────────┬─────────────────────────────────────────────────────┘
|
|
41
|
+
│
|
|
42
|
+
▼
|
|
43
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
44
|
+
│ Stage 2: Distributed Precision Downcasting │
|
|
45
|
+
│ • Downcasts DoubleType & DecimalType to 32-bit FloatType │
|
|
46
|
+
│ • Cuts executor memory consumption by ~50% during matrix aggregation │
|
|
47
|
+
└──────────────────────────────────────────────────┬─────────────────────────────────────────────────────┘
|
|
48
|
+
│
|
|
49
|
+
▼
|
|
50
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
51
|
+
│ Stage 3: High-Throughput Information Value (IV) Computation │
|
|
52
|
+
│ • Computes continuous quantiles and distributed binning via Spark mapInPandas │
|
|
53
|
+
│ • Aggregates Goods/Bads and calculates IV for numeric and categorical variables │
|
|
54
|
+
│ • Filters out variables with IV < iv_threshold │
|
|
55
|
+
└──────────────────────────────────────────────────┬─────────────────────────────────────────────────────┘
|
|
56
|
+
│
|
|
57
|
+
▼
|
|
58
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
59
|
+
│ Stage 4: IV-Prioritized Correlation Pruning │
|
|
60
|
+
│ • Computes Pearson correlation matrix via PySpark VectorAssembler + Correlation │
|
|
61
|
+
│ • Between collinear pairs (r >= corr_threshold), retains the feature with higher IV │
|
|
62
|
+
│ • Dynamic threshold relaxation ensures minimum required feature count is met │
|
|
63
|
+
└──────────────────────────────────────────────────┬─────────────────────────────────────────────────────┘
|
|
64
|
+
│
|
|
65
|
+
▼
|
|
66
|
+
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
|
|
67
|
+
│ Stage 5: Full Audit Reporting & Data Delivery │
|
|
68
|
+
│ • Generates comprehensive audit DataFrame (is_selected, iv, correlated_with, exclusion_reason) │
|
|
69
|
+
│ • Outputs pruned Spark DataFrame ready for Weight of Evidence (WoE) binning │
|
|
70
|
+
└────────────────────────────────────────────────────────────────────────────────────────────────────────┘
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Key Features
|
|
76
|
+
|
|
77
|
+
- ⚡ **Native PySpark Scalability**: Distributed quantile histograms and correlation matrices executed directly on cluster workers via Spark ML and `mapInPandas`.
|
|
78
|
+
- 📊 **IV-Driven Pruning**: When two features are collinear, the pipeline drops the weaker predictor and retains the variable with higher Information Value.
|
|
79
|
+
- 🛡️ **Mandatory Variable Protection**: Ensure business-critical variables (e.g., debt-to-income, credit bureau score) are never removed, regardless of their statistical properties.
|
|
80
|
+
- 📋 **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`).
|
|
81
|
+
- 🔄 **Dynamic Threshold Relaxation**: Automatically adjusts correlation thresholds if filtering becomes overly aggressive, keeping feature counts within target bounds (`expected_final_min`, `expected_final_max`).
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## Installation
|
|
86
|
+
|
|
87
|
+
### From PyPI
|
|
88
|
+
```bash
|
|
89
|
+
pip install feature-pruning
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### For Local Development
|
|
93
|
+
```bash
|
|
94
|
+
git clone https://github.com/vrukshya/feature_pruning.git
|
|
95
|
+
cd feature_pruning
|
|
96
|
+
pip install -e ".[dev]"
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### In Databricks / Cloud Notebooks
|
|
100
|
+
In your Databricks notebook cell:
|
|
101
|
+
```python
|
|
102
|
+
%pip install feature-pruning
|
|
103
|
+
```
|
|
104
|
+
Or add `feature-pruning` to your Databricks cluster libraries.
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## Quickstart
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from pyspark.sql import SparkSession
|
|
112
|
+
from feature_pruning import FeatureSelectionPipeline
|
|
113
|
+
|
|
114
|
+
# 1. Initialize Spark session (or use active session in Databricks/EMR)
|
|
115
|
+
spark = SparkSession.builder.appName("CreditRiskScorecard").getOrCreate()
|
|
116
|
+
|
|
117
|
+
# 2. Load credit training data
|
|
118
|
+
df = spark.table("risk_catalog.credit_data.application_train")
|
|
119
|
+
|
|
120
|
+
# 3. Configure the feature selection pipeline
|
|
121
|
+
pipeline = FeatureSelectionPipeline(
|
|
122
|
+
df=df,
|
|
123
|
+
target_col="default_flag", # 0 = Good loan, 1 = Default / Bad loan
|
|
124
|
+
mandatory_features=["bureau_score", "dti_ratio"], # Keep regardless of correlation
|
|
125
|
+
exclude_features=["application_id", "ssn_hash"], # Exclude identifiers
|
|
126
|
+
iv_threshold=0.03, # Industry baseline: IV >= 0.03
|
|
127
|
+
corr_threshold=0.95, # Multicollinearity cutoff
|
|
128
|
+
expected_final_min=20,
|
|
129
|
+
expected_final_max=150,
|
|
130
|
+
verbose=True,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
# 4. Execute pipeline
|
|
134
|
+
selected_spark_df, audit_report = pipeline.run()
|
|
135
|
+
|
|
136
|
+
# 5. Review results
|
|
137
|
+
print("Selected features count:", len(pipeline.get_selected_columns()))
|
|
138
|
+
print("Selected columns:", pipeline.get_selected_columns())
|
|
139
|
+
|
|
140
|
+
# 6. Inspect audit report
|
|
141
|
+
print(audit_report.head(20))
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
## Inspection & Diagnostic Methods
|
|
147
|
+
|
|
148
|
+
After calling `pipeline.run()`, several diagnostic helpers allow inspection of the feature reduction decisions:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
# 1. Retrieve list of final selected feature names
|
|
152
|
+
selected_features = pipeline.get_selected_columns()
|
|
153
|
+
|
|
154
|
+
# 2. Inspect Information Value ranking for all evaluated features
|
|
155
|
+
iv_summary = pipeline.get_iv_summary()
|
|
156
|
+
print(iv_summary.head(10))
|
|
157
|
+
|
|
158
|
+
# 3. Inspect which features were pruned due to correlation and their collinear counterpart
|
|
159
|
+
correlation_drops = pipeline.get_correlation_drops()
|
|
160
|
+
print(correlation_drops.head(10))
|
|
161
|
+
|
|
162
|
+
# 4. Full audit report with exact exclusion reasons
|
|
163
|
+
print(pipeline.feature_report_)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### Sample Audit Report Output
|
|
167
|
+
|
|
168
|
+
| feature | dtype | iv | correlated_with | correlation_value | is_selected | exclusion_reason |
|
|
169
|
+
|---|---|---|---|---|---|---|
|
|
170
|
+
| `bureau_score` | numeric | 0.4521 | None | None | True | |
|
|
171
|
+
| `utilization_rate`| numeric | 0.3180 | None | None | True | |
|
|
172
|
+
| `num_inquiries_6m` | numeric | 0.1420 | None | None | True | |
|
|
173
|
+
| `num_inquiries_3m` | numeric | 0.1210 | `num_inquiries_6m`| 0.965 | False | correlated (r=0.965) |
|
|
174
|
+
| `employer_name` | categorical | None | None | None | False | high_cardinality (>200) |
|
|
175
|
+
| `postal_code_raw`| numeric | 0.0120 | None | None | False | low_iv (0.0120) |
|
|
176
|
+
| `application_date`| datetime | None | None | None | False | datetime_column |
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
## API Reference
|
|
181
|
+
|
|
182
|
+
### `FeatureSelectionPipeline`
|
|
183
|
+
|
|
184
|
+
```python
|
|
185
|
+
FeatureSelectionPipeline(
|
|
186
|
+
df: SparkDataFrame,
|
|
187
|
+
target_col: str,
|
|
188
|
+
mandatory_features: Optional[List[str]] = None,
|
|
189
|
+
exclude_features: Optional[List[str]] = None,
|
|
190
|
+
iv_threshold: float = 0.03,
|
|
191
|
+
iv_n_bins: int = 100,
|
|
192
|
+
iv_sample_rows: int = 1_000_000,
|
|
193
|
+
corr_threshold: float = 0.95,
|
|
194
|
+
corr_sample_rows: int = 500_000,
|
|
195
|
+
max_corr_features: int = 5000,
|
|
196
|
+
max_cat_levels: int = 200,
|
|
197
|
+
expected_final_min: int = 200,
|
|
198
|
+
expected_final_max: int = 1000,
|
|
199
|
+
downcast: bool = True,
|
|
200
|
+
verbose: bool = True,
|
|
201
|
+
)
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
| Parameter | Type | Default | Description |
|
|
205
|
+
|---|---|---|---|
|
|
206
|
+
| `df` | `SparkDataFrame` | *Required* | Input Spark DataFrame containing raw candidate variables and target. |
|
|
207
|
+
| `target_col` | `str` | *Required* | Name of the binary target (0 = Good, 1 = Bad). Case-insensitive. |
|
|
208
|
+
| `mandatory_features` | `List[str]` | `None` | Columns guaranteed to be retained regardless of IV or correlation. |
|
|
209
|
+
| `exclude_features` | `List[str]` | `None` | Columns explicitly excluded from candidate pool (IDs, timestamps). |
|
|
210
|
+
| `iv_threshold` | `float` | `0.03` | Minimum Information Value (IV) required for feature inclusion. |
|
|
211
|
+
| `iv_n_bins` | `int` | `100` | Quantile bin resolution for continuous variable histogram computation. |
|
|
212
|
+
| `iv_sample_rows` | `int` | `1,000,000` | Sample ceiling for computing quantile thresholds on continuous columns. |
|
|
213
|
+
| `corr_threshold` | `float` | `0.95` | Pearson correlation ceiling. Collinear variable with lower IV is pruned. |
|
|
214
|
+
| `corr_sample_rows` | `int` | `500,000` | Sample ceiling for Pearson correlation matrix calculation. |
|
|
215
|
+
| `max_corr_features` | `int` | `5000` | Upper limit of top IV features fed into correlation assembler. |
|
|
216
|
+
| `max_cat_levels` | `int` | `200` | Maximum unique levels allowed before categorical is dropped as high-cardinality. |
|
|
217
|
+
| `expected_final_min` | `int` | `200` | Minimum retained count. Relaxes `corr_threshold` if pruned too aggressively. |
|
|
218
|
+
| `expected_final_max` | `int` | `1000` | Maximum cap on final retained variables. |
|
|
219
|
+
| `downcast` | `bool` | `True` | Downcasts Decimal/Double columns to Float32 to optimize Spark worker memory. |
|
|
220
|
+
| `verbose` | `bool` | `True` | Prints stage progress and execution timing logs. |
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## Credit Risk Scorecard Rules of Thumb
|
|
225
|
+
|
|
226
|
+
### Information Value (IV) Benchmarks
|
|
227
|
+
|
|
228
|
+
In credit risk modeling (Siddiqi, 2005), Information Value serves as the primary metric for filtering out uninformative signals:
|
|
229
|
+
|
|
230
|
+
| Information Value (IV) | Predictive Power | Action in Scorecard Development |
|
|
231
|
+
|---|---|---|
|
|
232
|
+
| **< 0.02** | Unpredictive | **Drop**: Adds noise and degrees of freedom without signal. |
|
|
233
|
+
| **0.02 – 0.10** | Weak Predictor | **Evaluate**: May be retained if part of a key credit policy dimension. |
|
|
234
|
+
| **0.10 – 0.30** | Medium Predictor | **Keep**: Core candidate for scorecard inclusion. |
|
|
235
|
+
| **0.30 – 0.50** | Strong Predictor | **Keep**: High diagnostic quality feature. |
|
|
236
|
+
| **> 0.50** | Suspicious / Too Good | **Investigate**: Often indicative of target leakage or operational bias. |
|
|
237
|
+
|
|
238
|
+
### Correlation Thresholds
|
|
239
|
+
|
|
240
|
+
- Standard practice sets the correlation threshold between `0.80` and `0.95`.
|
|
241
|
+
- Setting `corr_threshold=0.95` catches near-duplicate metrics (e.g., balance in dollars vs. balance in thousands).
|
|
242
|
+
- Setting `corr_threshold=0.85` produces a tighter, more orthogonal set of features that prevents variance inflation in final logistic regression models.
|
|
243
|
+
|
|
244
|
+
---
|
|
245
|
+
|
|
246
|
+
## Performance & Spark Optimization
|
|
247
|
+
|
|
248
|
+
- **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.
|
|
249
|
+
- **Spark Storage Management**: Intermediate working DataFrames are cached at `StorageLevel.MEMORY_AND_DISK` and unpersisted automatically at the conclusion of report generation.
|
|
250
|
+
- **Vector Correlation**: Correlation is calculated using Spark ML's native distributed linear algebra (`Correlation.corr`), supporting thousands of features simultaneously.
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
|
|
254
|
+
## Contributing
|
|
255
|
+
|
|
256
|
+
Contributions, bug reports, and feature requests are welcome!
|
|
257
|
+
Please feel free to submit a pull request or open an issue on GitHub.
|
|
258
|
+
|
|
259
|
+
1. Fork the Project
|
|
260
|
+
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
|
|
261
|
+
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
|
|
262
|
+
4. Push to the Branch (`git push origin feature/AmazingFeature`)
|
|
263
|
+
5. Open a Pull Request
|
|
264
|
+
|
|
265
|
+
---
|
|
266
|
+
|
|
267
|
+
## License
|
|
268
|
+
|
|
269
|
+
Distributed under the MIT License. See [LICENSE.txt](LICENSE.txt) for more details.
|
|
@@ -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
|
+
]
|