rapidsegment 1.2.2__tar.gz → 1.2.2.post1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rapidsegment
3
- Version: 1.2.2
3
+ Version: 1.2.2.post1
4
4
  Summary: A fast, multi-segment population scoring and combinatorial heuristic rule extraction engine.
5
5
  Author: Bishwarup Biswas
6
6
  Author-email: Bishwarup Biswas <bishwarup1429@gmail.com>
@@ -41,7 +41,7 @@ Description-Content-Type: text/markdown
41
41
  > This open‑source library (`RapidSegment`) is an independent, community‑driven predictive analytics framework. It is **completely unaffiliated** with any commercial products, SaaS platforms, or enterprise solutions of the same or similar name. Any overlap in nomenclature is purely coincidental.
42
42
 
43
43
  <p align="center">
44
- <img width="300" height="500" alt="adfd9cdf-251f-44e4-af79-20802d4a7a01" src="https://github.com/user-attachments/assets/803790d0-7ebe-4e79-a415-65f1daaea40b" />
44
+ <img width="1983" height="793" alt="f09fbbc6-17b6-4e86-96e7-5291a4175456" src="https://github.com/user-attachments/assets/f2584720-246b-4bda-b5a2-1b843bbec474" />
45
45
  </p>
46
46
 
47
47
  # 🚀 RapidSegment – Strategic Segmentation & Scorecard Engine
@@ -71,13 +71,14 @@ Description-Content-Type: text/markdown
71
71
 
72
72
  ## ✨ Features
73
73
 
74
- - **🔎 Automated Rule Discovery** – Uses Optimal Binning + Apriori pruning to find multi‑way (1‑, 2‑, 3‑way) conditions that maximise lift and volume.
74
+ - **🔎 Automated Rule Discovery** – Uses Optimal Binning (or fast naive quantile binning) + Apriori pruning to find multi‑way (1‑, 2‑, 3‑way) conditions that maximise lift and volume.
75
75
  - **🧩 Hierarchical Segments** – Extracts mutually exclusive rules sequentially on a shrinking residual dataset, ensuring clean portfolio decomposition.
76
- - **⚡ Hyper‑Efficient** – Leverages **DuckDB** for vectorised SQL aggregations and **NumPy** (or DuckDB’s native quantiles) for blazing‑fast scoring.
76
+ - **🔀 Adjacent-Bin Expansion** – Optionally merges neighbouring bins (`max_expansion_hops`) to recover higher-event rules that pure single-bin candidates miss.
77
+ - **⚡ Hyper‑Efficient & Out-of-Core** – Leverages **DuckDB** (disk-backed by default) for vectorised SQL aggregations; spills to disk so large datasets fit in limited RAM.
77
78
  - **☁️ BigQuery Ready** – Optional feature screening runs natively inside Google BigQuery, downloading only the most predictive columns.
78
79
  - **📦 Production‑Ready Outputs** – Exports pure ANSI SQL filters and a JSON scorecard with decile thresholds, ready for deployment.
79
80
  - **📊 Transparent Weighting** – Uses the segment response rate to compute intuitive integer weights, while retaining lift, response rate, and capture rate for each segment.
80
- - **🔬 Audit Trail** – Built‑in diagnostic (`explain_feature_journey`) to trace any feature’s lifecycle through the extraction process.
81
+ - **🔬 Full Audit Trail** – `explain_feature_journey`, `explain_no_segments`, and `generate_feature_health_report` for complete diagnostics.
81
82
 
82
83
  ---
83
84
 
@@ -134,14 +135,16 @@ builder = StrategicSegmentBuilder(
134
135
  top_n_vars=15,
135
136
  max_segments=5,
136
137
  max_feature_reuse=1,
137
- param_grid={"min_sample_size": [1000,2500,5000], "min_lift": [2.0,3.5,5.0]},
138
+ param_grid={"min_sample_size": [1000, 2500, 5000], "min_lift": [1.5, 2.0, 3.0]},
138
139
  enable_diversity=True,
139
140
  feature_groups={
140
141
  "delinquency": ["max_dpd_12m", "risk_segment"],
141
142
  "utilization": ["utilization_avg_3m"]
142
143
  },
143
144
  ignore_features=["cust_id"],
144
- sort_priority="lift_rate_count"
145
+ sort_priority="rate_lift_count", # current default
146
+ binning_method="optimal", # or "naive"
147
+ max_expansion_hops=1, # enable adjacent-bin expansion
145
148
  )
146
149
 
147
150
  # 3. Extract hierarchical segments
@@ -202,7 +205,10 @@ flowchart LR
202
205
  ### 🔍 `StrategicSegmentBuilder`
203
206
  - **Purpose**: The core segmentation engine. It discovers high‑lift rules using Optimal Binning + Apriori pruning + grid search.
204
207
  - **Outputs**: A list of segments, each with a pure ANSI SQL `WHERE` clause, plus metrics (count, rate, lift).
205
- - **Unique Feature**: Built‑in diagnostic (`explain_feature_journey`) to audit feature usage across iterations.
208
+ - **Diagnostics**
209
+ - `explain_feature_journey(feature)` – full audit trail of a feature across iterations.
210
+ - `explain_no_segments()` – human-readable report explaining why extraction stopped early or returned zero segments.
211
+ - `generate_feature_health_report(data, features)` – DuckDB-native bin-level health report (counts, events, response rate, missing flag).
206
212
 
207
213
  ### 📊 `StrategicSegmentScore`
208
214
  - **Purpose**: Converts binary segment flags into a weighted scorecard with decile thresholds.
@@ -304,6 +310,31 @@ flowchart TD
304
310
  ### 1. Feature Ranking & Binning
305
311
  Optimal Binning (via `optbinning`) computes the Information Value (IV) for each feature, automatically handling categorical and numerical types. Only the top `top_n_vars` features proceed.
306
312
 
313
+ ### Naive Binning (Fast Quantile Path)
314
+
315
+ When `binning_method="naive"`, the engine skips OptBinning and builds bins directly inside DuckDB:
316
+
317
+ **Numerical features**
318
+ - Compute `naive_bins` quantiles with `QUANTILE_CONT`.
319
+ - Force the outermost edges to `-∞` and `+∞`.
320
+ - Assign every row to a half-open interval: `[lower, upper)`.
321
+ - Nulls go into a dedicated `Missing` bin.
322
+
323
+ **Categorical features**
324
+ - Each distinct value becomes its own bin: `[value]`.
325
+ - Null / empty / “None” / “nan” values are grouped into `Missing`.
326
+
327
+ **Why it exists**
328
+ - Extremely fast on large data (pure SQL, no Python loops).
329
+ - Produces stable, equal-frequency bins that are easy to interpret.
330
+ - Works seamlessly with **adjacent-bin expansion** (`max_expansion_hops > 0`), which can later merge neighbouring bins to recover higher-event rules.
331
+
332
+ **Trade-off**
333
+ - Optimal Binning usually finds slightly more predictive cut-points.
334
+ - Naive binning is preferred when speed or simplicity matters more than maximal IV.
335
+
336
+ Both paths feed the same downstream pipeline (IV ranking → Apriori → expansion → champion selection).
337
+
307
338
  ### 2. Apriori Pruning
308
339
  The engine evaluates combinations in a layered fashion:
309
340
 
@@ -376,18 +407,25 @@ Scores are computed as the sum of weights for all segments a customer triggers.
376
407
  | Parameter | Type | Default | Description |
377
408
  |-----------|------|---------|-------------|
378
409
  | `target` | `str` | **Required** | Binary target column name. |
379
- | `n_jobs` | `int` | `-1` | Number of parallel workers. |
380
- | `min_sample_size` | `int` | `1000` | Minimum rows for a rule. |
381
- | `min_lift` | `float` | `2.0` | Minimum lift ratio. |
382
- | `min_events` | `int` | `5` | Minimum positive events. |
383
- | `top_n_vars` | `int` | `20` | Number of top‑IV features to consider. |
410
+ | `n_jobs` | `int` | `-1` | Parallel workers for IV/binning (`-1` = all but one core). |
411
+ | `min_sample_size` | `int` | `1000` | Absolute minimum rows for a valid rule. |
412
+ | `min_lift` | `float` | `1.5` | Absolute minimum lift (hard constraint). |
413
+ | `min_events` | `int` | `100` | Minimum positive events for a valid rule. |
414
+ | `top_n_vars` | `int` | `15` | Number of top features passed to the Apriori engine. |
384
415
  | `max_segments` | `int` | `10` | Maximum segments to extract. |
385
- | `max_feature_reuse` | `int` | `1` | How many times a feature can appear. |
386
- | `enable_diversity` | `bool` | `False` | Prevent same‑group feature combinations. |
387
- | `enable_1way/2way/3way` | `bool` | `True` | Toggle rule complexity levels. |
388
- | `feature_groups` | `dict` | `{}` | Business‑category mapping for diversity. |
389
- | `ignore_features` | `list` | `[]` | Columns to drop before processing. |
390
- | `sort_priority` | `STR` | `lift_count_rate` | Order in which rules will ranked and selected. Sample capture heavy/Response Rate Heavy/Lift Heavy. |
416
+ | `max_feature_reuse` | `int` | `1` | Max times any single feature may appear across segments. |
417
+ | `param_grid` | `dict` | `{}` | Optional grid of `{min_sample_size, min_lift}` to sweep. |
418
+ | `enable_diversity` | `bool` | `False` | Block combinations that mix features from the same group. |
419
+ | `enable_1way` / `enable_2way` / `enable_3way` | `bool` | `True` | Toggle 1-, 2-, and 3-way rules. |
420
+ | `feature_groups` | `dict` | `{}` | Business-category → column list (used by diversity). |
421
+ | `ignore_features` | `list` | `[]` | Columns to exclude before IV calculation. |
422
+ | `sort_priority` | `str` | `"rate_lift_count"` | Ranking key for champion selection (many variants supported). |
423
+ | `binning_method` | `str` | `"optimal"` | `"optimal"` (OptBinning) or `"naive"` (quantile bins). |
424
+ | `naive_bins` | `int` | `5` | Number of quantile bins when `binning_method="naive"`. |
425
+ | `max_expansion_hops` | `int` | `0` | Adjacent-bin merge distance (0 = disabled). |
426
+ | `selection_metric` | `str` | `"iv"` | Rank features by `"iv"` or `"response_rate"`. |
427
+ | `expand_log_mode` | `str` | `"none"` | Expansion logging: `"none"` \| `"summary"` \| `"champion"` \| `"full"`. |
428
+ | `db_path` / `db_temp_dir` | `str` | `None` | Optional explicit DuckDB file + temp dir (auto-created otherwise). |
391
429
 
392
430
  **Output** – list of dicts with keys: `segment_id`, `rule_string`, `sql_filter`, `count`, `rate`, `lift`, `meta_applied_sample_size`, `meta_applied_min_lift`.
393
431
 
@@ -441,7 +479,7 @@ This project is licensed under the MIT License – see the [LICENSE](LICENSE) fi
441
479
 
442
480
  ---
443
481
 
444
- **Built with ❤️ by Bishwarup Biswas, Gemini & DeepSeek.**
482
+ **Built with ❤️ by Bishwarup Biswas**
445
483
  Special Thanks to Mr. [Guillermo Navas Palencia](https://github.com/guillermo-navas-palencia) for creating [Optbinning](https://github.com/guillermo-navas-palencia/optbinning) library.
446
484
 
447
485
  _Independent, open‑source, and ready for production._
@@ -4,7 +4,7 @@
4
4
  > This open‑source library (`RapidSegment`) is an independent, community‑driven predictive analytics framework. It is **completely unaffiliated** with any commercial products, SaaS platforms, or enterprise solutions of the same or similar name. Any overlap in nomenclature is purely coincidental.
5
5
 
6
6
  <p align="center">
7
- <img width="300" height="500" alt="adfd9cdf-251f-44e4-af79-20802d4a7a01" src="https://github.com/user-attachments/assets/803790d0-7ebe-4e79-a415-65f1daaea40b" />
7
+ <img width="1983" height="793" alt="f09fbbc6-17b6-4e86-96e7-5291a4175456" src="https://github.com/user-attachments/assets/f2584720-246b-4bda-b5a2-1b843bbec474" />
8
8
  </p>
9
9
 
10
10
  # 🚀 RapidSegment – Strategic Segmentation & Scorecard Engine
@@ -34,13 +34,14 @@
34
34
 
35
35
  ## ✨ Features
36
36
 
37
- - **🔎 Automated Rule Discovery** – Uses Optimal Binning + Apriori pruning to find multi‑way (1‑, 2‑, 3‑way) conditions that maximise lift and volume.
37
+ - **🔎 Automated Rule Discovery** – Uses Optimal Binning (or fast naive quantile binning) + Apriori pruning to find multi‑way (1‑, 2‑, 3‑way) conditions that maximise lift and volume.
38
38
  - **🧩 Hierarchical Segments** – Extracts mutually exclusive rules sequentially on a shrinking residual dataset, ensuring clean portfolio decomposition.
39
- - **⚡ Hyper‑Efficient** – Leverages **DuckDB** for vectorised SQL aggregations and **NumPy** (or DuckDB’s native quantiles) for blazing‑fast scoring.
39
+ - **🔀 Adjacent-Bin Expansion** – Optionally merges neighbouring bins (`max_expansion_hops`) to recover higher-event rules that pure single-bin candidates miss.
40
+ - **⚡ Hyper‑Efficient & Out-of-Core** – Leverages **DuckDB** (disk-backed by default) for vectorised SQL aggregations; spills to disk so large datasets fit in limited RAM.
40
41
  - **☁️ BigQuery Ready** – Optional feature screening runs natively inside Google BigQuery, downloading only the most predictive columns.
41
42
  - **📦 Production‑Ready Outputs** – Exports pure ANSI SQL filters and a JSON scorecard with decile thresholds, ready for deployment.
42
43
  - **📊 Transparent Weighting** – Uses the segment response rate to compute intuitive integer weights, while retaining lift, response rate, and capture rate for each segment.
43
- - **🔬 Audit Trail** – Built‑in diagnostic (`explain_feature_journey`) to trace any feature’s lifecycle through the extraction process.
44
+ - **🔬 Full Audit Trail** – `explain_feature_journey`, `explain_no_segments`, and `generate_feature_health_report` for complete diagnostics.
44
45
 
45
46
  ---
46
47
 
@@ -97,14 +98,16 @@ builder = StrategicSegmentBuilder(
97
98
  top_n_vars=15,
98
99
  max_segments=5,
99
100
  max_feature_reuse=1,
100
- param_grid={"min_sample_size": [1000,2500,5000], "min_lift": [2.0,3.5,5.0]},
101
+ param_grid={"min_sample_size": [1000, 2500, 5000], "min_lift": [1.5, 2.0, 3.0]},
101
102
  enable_diversity=True,
102
103
  feature_groups={
103
104
  "delinquency": ["max_dpd_12m", "risk_segment"],
104
105
  "utilization": ["utilization_avg_3m"]
105
106
  },
106
107
  ignore_features=["cust_id"],
107
- sort_priority="lift_rate_count"
108
+ sort_priority="rate_lift_count", # current default
109
+ binning_method="optimal", # or "naive"
110
+ max_expansion_hops=1, # enable adjacent-bin expansion
108
111
  )
109
112
 
110
113
  # 3. Extract hierarchical segments
@@ -165,7 +168,10 @@ flowchart LR
165
168
  ### 🔍 `StrategicSegmentBuilder`
166
169
  - **Purpose**: The core segmentation engine. It discovers high‑lift rules using Optimal Binning + Apriori pruning + grid search.
167
170
  - **Outputs**: A list of segments, each with a pure ANSI SQL `WHERE` clause, plus metrics (count, rate, lift).
168
- - **Unique Feature**: Built‑in diagnostic (`explain_feature_journey`) to audit feature usage across iterations.
171
+ - **Diagnostics**
172
+ - `explain_feature_journey(feature)` – full audit trail of a feature across iterations.
173
+ - `explain_no_segments()` – human-readable report explaining why extraction stopped early or returned zero segments.
174
+ - `generate_feature_health_report(data, features)` – DuckDB-native bin-level health report (counts, events, response rate, missing flag).
169
175
 
170
176
  ### 📊 `StrategicSegmentScore`
171
177
  - **Purpose**: Converts binary segment flags into a weighted scorecard with decile thresholds.
@@ -267,6 +273,31 @@ flowchart TD
267
273
  ### 1. Feature Ranking & Binning
268
274
  Optimal Binning (via `optbinning`) computes the Information Value (IV) for each feature, automatically handling categorical and numerical types. Only the top `top_n_vars` features proceed.
269
275
 
276
+ ### Naive Binning (Fast Quantile Path)
277
+
278
+ When `binning_method="naive"`, the engine skips OptBinning and builds bins directly inside DuckDB:
279
+
280
+ **Numerical features**
281
+ - Compute `naive_bins` quantiles with `QUANTILE_CONT`.
282
+ - Force the outermost edges to `-∞` and `+∞`.
283
+ - Assign every row to a half-open interval: `[lower, upper)`.
284
+ - Nulls go into a dedicated `Missing` bin.
285
+
286
+ **Categorical features**
287
+ - Each distinct value becomes its own bin: `[value]`.
288
+ - Null / empty / “None” / “nan” values are grouped into `Missing`.
289
+
290
+ **Why it exists**
291
+ - Extremely fast on large data (pure SQL, no Python loops).
292
+ - Produces stable, equal-frequency bins that are easy to interpret.
293
+ - Works seamlessly with **adjacent-bin expansion** (`max_expansion_hops > 0`), which can later merge neighbouring bins to recover higher-event rules.
294
+
295
+ **Trade-off**
296
+ - Optimal Binning usually finds slightly more predictive cut-points.
297
+ - Naive binning is preferred when speed or simplicity matters more than maximal IV.
298
+
299
+ Both paths feed the same downstream pipeline (IV ranking → Apriori → expansion → champion selection).
300
+
270
301
  ### 2. Apriori Pruning
271
302
  The engine evaluates combinations in a layered fashion:
272
303
 
@@ -339,18 +370,25 @@ Scores are computed as the sum of weights for all segments a customer triggers.
339
370
  | Parameter | Type | Default | Description |
340
371
  |-----------|------|---------|-------------|
341
372
  | `target` | `str` | **Required** | Binary target column name. |
342
- | `n_jobs` | `int` | `-1` | Number of parallel workers. |
343
- | `min_sample_size` | `int` | `1000` | Minimum rows for a rule. |
344
- | `min_lift` | `float` | `2.0` | Minimum lift ratio. |
345
- | `min_events` | `int` | `5` | Minimum positive events. |
346
- | `top_n_vars` | `int` | `20` | Number of top‑IV features to consider. |
373
+ | `n_jobs` | `int` | `-1` | Parallel workers for IV/binning (`-1` = all but one core). |
374
+ | `min_sample_size` | `int` | `1000` | Absolute minimum rows for a valid rule. |
375
+ | `min_lift` | `float` | `1.5` | Absolute minimum lift (hard constraint). |
376
+ | `min_events` | `int` | `100` | Minimum positive events for a valid rule. |
377
+ | `top_n_vars` | `int` | `15` | Number of top features passed to the Apriori engine. |
347
378
  | `max_segments` | `int` | `10` | Maximum segments to extract. |
348
- | `max_feature_reuse` | `int` | `1` | How many times a feature can appear. |
349
- | `enable_diversity` | `bool` | `False` | Prevent same‑group feature combinations. |
350
- | `enable_1way/2way/3way` | `bool` | `True` | Toggle rule complexity levels. |
351
- | `feature_groups` | `dict` | `{}` | Business‑category mapping for diversity. |
352
- | `ignore_features` | `list` | `[]` | Columns to drop before processing. |
353
- | `sort_priority` | `STR` | `lift_count_rate` | Order in which rules will ranked and selected. Sample capture heavy/Response Rate Heavy/Lift Heavy. |
379
+ | `max_feature_reuse` | `int` | `1` | Max times any single feature may appear across segments. |
380
+ | `param_grid` | `dict` | `{}` | Optional grid of `{min_sample_size, min_lift}` to sweep. |
381
+ | `enable_diversity` | `bool` | `False` | Block combinations that mix features from the same group. |
382
+ | `enable_1way` / `enable_2way` / `enable_3way` | `bool` | `True` | Toggle 1-, 2-, and 3-way rules. |
383
+ | `feature_groups` | `dict` | `{}` | Business-category → column list (used by diversity). |
384
+ | `ignore_features` | `list` | `[]` | Columns to exclude before IV calculation. |
385
+ | `sort_priority` | `str` | `"rate_lift_count"` | Ranking key for champion selection (many variants supported). |
386
+ | `binning_method` | `str` | `"optimal"` | `"optimal"` (OptBinning) or `"naive"` (quantile bins). |
387
+ | `naive_bins` | `int` | `5` | Number of quantile bins when `binning_method="naive"`. |
388
+ | `max_expansion_hops` | `int` | `0` | Adjacent-bin merge distance (0 = disabled). |
389
+ | `selection_metric` | `str` | `"iv"` | Rank features by `"iv"` or `"response_rate"`. |
390
+ | `expand_log_mode` | `str` | `"none"` | Expansion logging: `"none"` \| `"summary"` \| `"champion"` \| `"full"`. |
391
+ | `db_path` / `db_temp_dir` | `str` | `None` | Optional explicit DuckDB file + temp dir (auto-created otherwise). |
354
392
 
355
393
  **Output** – list of dicts with keys: `segment_id`, `rule_string`, `sql_filter`, `count`, `rate`, `lift`, `meta_applied_sample_size`, `meta_applied_min_lift`.
356
394
 
@@ -404,7 +442,7 @@ This project is licensed under the MIT License – see the [LICENSE](LICENSE) fi
404
442
 
405
443
  ---
406
444
 
407
- **Built with ❤️ by Bishwarup Biswas, Gemini & DeepSeek.**
445
+ **Built with ❤️ by Bishwarup Biswas**
408
446
  Special Thanks to Mr. [Guillermo Navas Palencia](https://github.com/guillermo-navas-palencia) for creating [Optbinning](https://github.com/guillermo-navas-palencia/optbinning) library.
409
447
 
410
448
  _Independent, open‑source, and ready for production._
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rapidsegment"
3
- version = "1.2.2"
3
+ version = "1.2.2.post1"
4
4
  description = "A fast, multi-segment population scoring and combinatorial heuristic rule extraction engine."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rapidsegment"
3
- version = "1.2.2"
3
+ version = "1.2.2.post1"
4
4
  description = "A fast, multi-segment population scoring and combinatorial heuristic rule extraction engine."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -95,7 +95,8 @@ class StrategicSegmentBuilder:
95
95
  feature_groups: Optional[Dict[str, List[str]]] = None,
96
96
  ignore_features: Optional[List[str]] = None,
97
97
  sort_priority: str = "rate_lift_count",
98
- binning_method: str = "optimal_cart", # "naive" | "optimal_cart" | "optimal_quantile" | "optimal" (alias of cart) naive_bins: int = 5 ,
98
+ binning_method: str = "optimal_cart", # "naive" | "optimal_cart" | "optimal_quantile" | "optimal" (alias of cart)
99
+ naive_bins: int = 5 ,
99
100
  max_expansion_hops: int = 0,
100
101
  selection_metric: str = "iv",
101
102
  expand_log_mode: str = "none",
@@ -1964,4 +1965,4 @@ class StrategicSegmentBuilder:
1964
1965
  })
1965
1966
 
1966
1967
  health_report_df = pd.DataFrame(rows)
1967
- return health_report_df
1968
+ return health_report_df
File without changes