lamp-knn 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.
lamp_knn-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kodetr
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,233 @@
1
+ Metadata-Version: 2.4
2
+ Name: lamp-knn
3
+ Version: 0.1.0
4
+ Summary: Latency-Aware Majority Prototype Selection for KNN with Voronoi mass conservation and Bayesian prior calibration on imbalanced tabular data.
5
+ Author-email: kodetr <t4nwi12@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://pypi.org/project/lamp-knn/
8
+ Project-URL: Documentation, https://pypi.org/project/lamp-knn/
9
+ Keywords: knn,k-nearest-neighbors,imbalanced-learning,prototype-selection,voronoi,latency-aware,tabular-classification,scikit-learn
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: numpy>=1.23
27
+ Requires-Dist: scipy>=1.10
28
+ Requires-Dist: scikit-learn>=1.2
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0; extra == "dev"
31
+ Requires-Dist: build>=1.0; extra == "dev"
32
+ Requires-Dist: twine>=5.0; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # LAMP-KNN
36
+
37
+ **Latency-Aware Majority Prototype Selection for Imbalanced Tabular KNN**
38
+
39
+ [![Python](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://pypi.org/project/lamp-knn/)
40
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
41
+
42
+ `lamp-knn` is a lightweight, **scikit-learn compatible** Python library implementing **LAMP-KNN**, a prototype-selection *K-Nearest Neighbors* classifier specifically designed for **binary imbalanced tabular data** under strict single-row inference latency budgets.
43
+
44
+ Unlike naive majority undersampling (which discards majority observations without compensating density distortion and suffers class inversion on low-imbalance datasets), LAMP-KNN combines four mathematical mechanisms:
45
+
46
+ 1. **Continuous Margin Boundary Ranking & Interior Clustering** — Ranks majority candidates by `(-minority_neighbor_count, dist_to_nearest_minority)` in round-robin order per minority point (eliminating zero-boundary starvation on separated or high-dimensional data) and fills the remaining quota from K-means interior clusters while retaining **100% of minority training samples**.
47
+ 2. **Exact Voronoi Mass Conservation** — Assigns each retained majority prototype *p*ⱼ ∈ *S*₀ its exact Voronoi cell mass *m*ⱼ (Σ *m*ⱼ = *N*₀), preserving full-dataset majority density at any compression ratio and preventing class inversion.
48
+ 3. **Full-Data Cached Local Posterior Evidence** — Computes Laplace-smoothed local minority posterior evidence *e*ᵢ on the full training set *prior* to majority pruning so retained prototypes preserve neighborhood purity.
49
+ 4. **Bayesian Prior-Calibrated Signed-Evidence Inference** — Precomputes signed prototype evidence *v*ᵢ = *m*ᵢ^β (*e*ᵢ − τ(γ)) with prior threshold τ(γ) = *r*\_π^γ / (1 + *r*\_π^γ) offline, reducing single-row prediction to **one compressed `cKDTree` query and one NumPy dot product** with direct NumPy standardization (avoiding scikit-learn's ~40 µs single-row `StandardScaler.transform` wrapper overhead).
50
+
51
+ ---
52
+
53
+ ## Empirical Highlights (20 Independent KEEL Datasets, 100 Folds)
54
+
55
+ Under independent latency-constrained tuning (`p95 <= 0.80 * standard KNN`, identical direct NumPy standardization, 3 interleaved test timing sessions):
56
+
57
+ | Method | Mean Macro-F1 (Rank) | Mean Minority-F1 | Mean Bal. Acc. | Mean p95 Latency (µs) | 3-Session Target Attainment | Median Total Break-Even (Queries) |
58
+ |---|---:|---:|---:|---:|---:|---:|
59
+ | **LAMP-KNN** | **0.814 (#1)** | **0.681 (#1)** | 0.833 (#2) | **13.15 (#1)** | **65 / 100** | **88,469** |
60
+ | KNN-BPP (full ref.) | 0.812 (#3) | 0.680 (#2) | 0.847 (#1) | 27.68 (#6) | — | — |
61
+ | CABLE-kNN (full ref.) | 0.810 (#2) | 0.666 (#3) | 0.818 (#4) | 30.37 (#7) | — | — |
62
+ | Standard KNN (full ref.) | 0.791 (#4) | 0.622 (#5) | 0.785 (#7) | 29.59 (#5) | — | — |
63
+ | Random undersampling | 0.773 (#5) | 0.646 (#4) | 0.823 (#3) | 16.56 (#2) | 52 / 100 | 91,457 |
64
+ | CIS multi-cluster | 0.771 (#6) | 0.645 (#5) | 0.816 (#5) | 16.68 (#3) | 47 / 100 | 433,974 |
65
+ | NearMiss-3 | 0.745 (#7) | 0.618 (#7) | 0.786 (#6) | 16.93 (#4) | 44 / 100 | 94,554 |
66
+
67
+ - **Statistically significant Macro-F1 wins** (Friedman χ² = 14.585, *p* = 0.0238; Holm-corrected Wilcoxon): outperforms **NearMiss-3** (*p*\_Holm = 0.0032), **CIS multi-cluster** (*p*\_Holm = 0.0145), and **Random undersampling** (*p*\_Holm = 0.0356).
68
+ - **Statistically significant p95 latency wins against all 6 baselines** (*p*\_Holm ≤ 0.0100; 20/20 wins over full-reference KNN, KNN-BPP, and CABLE-kNN at *p*\_Holm = 1.14 × 10⁻⁵).
69
+ - **Strong out-of-panel generalization:** On 6 untouched KEEL datasets, frozen LAMP-KNN again ranks **#1 on Macro-F1**, **#1 on Minority-F1**, and **#1 fastest on single-row p95 latency** (`12.45 µs`).
70
+
71
+ ---
72
+
73
+ ## Installation
74
+
75
+ ```bash
76
+ pip install lamp-knn
77
+ ```
78
+
79
+ Requires Python `>= 3.9`, `numpy >= 1.23`, `scipy >= 1.10`, and `scikit-learn >= 1.2`.
80
+
81
+ ---
82
+
83
+ ## Quickstart
84
+
85
+ ### 1. Drop-In Scikit-Learn Usage (Fast Fixed-Parameter Mode)
86
+
87
+ ```python
88
+ from sklearn.datasets import make_classification
89
+ from sklearn.metrics import classification_report, f1_score
90
+ from sklearn.model_selection import train_test_split
91
+ from lamp_knn import LampKNNClassifier
92
+
93
+ X, y = make_classification(
94
+ n_samples=3000,
95
+ n_features=20,
96
+ n_informative=10,
97
+ weights=[0.95, 0.05],
98
+ random_state=42,
99
+ )
100
+ X_train, X_test, y_train, y_test = train_test_split(
101
+ X, y, test_size=0.2, stratify=y, random_state=42
102
+ )
103
+
104
+ clf = LampKNNClassifier(
105
+ n_neighbors=5,
106
+ majority_fraction=0.25, # keep 25% of majority + 100% of minority
107
+ boundary_fraction=0.50,
108
+ voronoi_beta=1.0, # exact Voronoi mass conservation
109
+ prior_gamma=0.5, # Bayesian prior calibration
110
+ evidence_neighbors=0, # 0 for exact labels, or 3/7 for noisy overlap
111
+ standardize=True, # built-in direct NumPy z-score standardization
112
+ random_state=42,
113
+ )
114
+ clf.fit(X_train, y_train)
115
+
116
+ y_pred = clf.predict(X_test)
117
+ print(f"Macro-F1: {f1_score(y_test, y_pred, average='macro'):.4f}")
118
+ print(f"Prototypes kept: {clf.n_prototypes_} / {len(X_train)} ({clf.compression_ratio_:.1%})")
119
+ print(classification_report(y_test, y_pred))
120
+ ```
121
+
122
+ ### 2. Automatic Latency-Constrained Tuning (`auto_tune=True`)
123
+
124
+ Use `auto_tune=True` to run the full latency-constrained protocol from the paper: vectorized NumPy quality selection over all 72 scoring rules per `(budget, boundary_fraction, k)`, followed by 3-session interleaved p95 latency profiling on at most 16 `(budget, k)` representatives subject to `p95 <= latency_ratio * full_knn_p95`.
125
+
126
+ ```python
127
+ from lamp_knn import LampKNNClassifier
128
+
129
+ clf = LampKNNClassifier(
130
+ auto_tune=True,
131
+ latency_ratio=0.80, # target p95 <= 80% of standard full-reference KNN
132
+ standardize=True,
133
+ random_state=42,
134
+ )
135
+ clf.fit(X_train, y_train)
136
+
137
+ print("Selected hyperparameters:", clf.selected_params_)
138
+ print("Validation tuning summary:", clf.tuning_info_)
139
+ y_pred = clf.predict(X_test)
140
+ ```
141
+
142
+ ### 3. Ultra-Fast Single-Row Inference (`predict_one`)
143
+
144
+ For low-latency online serving (e.g., fraud or anomaly scoring one event at a time), call `predict_one(x)` to bypass 2D batch validation overhead and execute direct NumPy standardization + compressed `cKDTree` query + dot product:
145
+
146
+ ```python
147
+ single_event = X_test[0] # 1D NumPy array of shape (n_features,)
148
+ label = clf.predict_one(single_event)
149
+ ```
150
+
151
+ > **Performance tip:** Keep `standardize=True` inside `LampKNNClassifier` instead of wrapping it after `sklearn.preprocessing.StandardScaler` in single-row loops. Calling `StandardScaler.transform(x[None, :])` per row adds ~40 µs of Python validation overhead, whereas built-in NumPy standardization adds only ~0.6–0.8 µs.
152
+
153
+ ### 4. Probabilities, Decision Scores, Arbitrary Labels & Cross-Validation
154
+
155
+ `LampKNNClassifier` works with arbitrary binary labels (e.g., `["legit", "fraud"]` or `[-1, 1]`), automatically identifies the minority class, and supports `decision_function`, `predict_proba`, `cross_val_score`, `GridSearchCV`, and `Pipeline`:
156
+
157
+ ```python
158
+ from sklearn.metrics import average_precision_score, roc_auc_score
159
+ from sklearn.model_selection import StratifiedKFold, cross_val_score
160
+
161
+ scores = clf.decision_function(X_test)
162
+ probas = clf.predict_proba(X_test)[:, 1]
163
+ print("ROC-AUC:", roc_auc_score(y_test, scores))
164
+ print("PR-AUC: ", average_precision_score(y_test, probas))
165
+
166
+ cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
167
+ f1_cv = cross_val_score(
168
+ LampKNNClassifier(majority_fraction=0.25, prior_gamma=0.5, random_state=42),
169
+ X, y, cv=cv, scoring="f1_macro",
170
+ )
171
+ print(f"5-fold Macro-F1: {f1_cv.mean():.4f} +/- {f1_cv.std():.4f}")
172
+ ```
173
+
174
+ ### 5. Low-Level Prototype Selection API (`LampPrototypeSelector`)
175
+
176
+ If you want to inspect or reuse the selected prototypes, exact Voronoi masses, or full-data cached local evidence directly:
177
+
178
+ ```python
179
+ import numpy as np
180
+ from lamp_knn import LampPrototypeSelector
181
+
182
+ # Assumes X_scaled is standardized and y_bin is encoded as 0 (majority) / 1 (minority)
183
+ selector = LampPrototypeSelector(X_scaled, y_bin, neighborhood_size=11, random_state=42)
184
+ rows, masses = selector.select_with_voronoi_mass(majority_budget=300, boundary_fraction=0.5)
185
+ evidence = selector.local_evidence(h_ev=7, alpha=1.0)[rows]
186
+
187
+ assert np.isclose(masses[y_bin[rows] == 0].sum(), np.count_nonzero(y_bin == 0))
188
+ ```
189
+
190
+ ---
191
+
192
+ ## Key Parameters & Practical Guidance
193
+
194
+ | Parameter | Default | Description & Recommended Usage |
195
+ |---|---:|---|
196
+ | `n_neighbors` | `5` | Number of nearest prototype neighbors *k* (`auto_tune=False`). |
197
+ | `majority_fraction` | `0.25` | Share of majority rows kept (`0.10–0.50` for *N* ≥ 1,000 or *d* ≥ 20). |
198
+ | `boundary_fraction` | `0.5` | Share of majority budget allocated to continuous margin boundary points. |
199
+ | `voronoi_beta` | `1.0` | Voronoi mass exponent β ≥ 0 (`1.0` prevents class inversion on low-IR data; `0.5` softens extreme masses). |
200
+ | `prior_gamma` | `0.5` | Prior threshold exponent γ ∈ [0, 1] (`0.0` favors precision/standard posterior; `0.5–0.75` maximizes Macro-F1; `1.0` maximizes G-mean/Balanced Accuracy). |
201
+ | `evidence_neighbors` | `0` | Full-data cached local evidence *h*\_ev (`0` safest on ultra-sparse high-dimensional data; `3` or `7` helpful on noisy overlapping regimes). |
202
+ | `rank_rho` | `0.0` | Neighbor rank weighting (`0.0` uniform; `1.0` inverse-rank `1/r`). |
203
+ | `standardize` | `True` | Built-in direct NumPy z-score standardization `(x - mean_) / scale_`. |
204
+ | `auto_tune` | `False` | Enables internal validation search + 3-session p95 latency selection over ≤ 16 representatives. |
205
+ | `latency_ratio` | `0.80` | Maximum allowed validation p95 ratio vs. full-reference KNN when `auto_tune=True`. |
206
+
207
+ ### Fitted Attributes
208
+
209
+ After calling `fit(X, y)`:
210
+
211
+ - `classes_`, `majority_class_`, `minority_class_` — Detected binary classes.
212
+ - `prototype_indices_` — Row indices of retained prototypes (all minority rows + selected majority prototypes).
213
+ - `voronoi_masses_` — Exact Voronoi mass assigned to each prototype.
214
+ - `signed_values_` — Precomputed signed-evidence vector *v*ᵢ = *m*ᵢ^β (*e*ᵢ − τ(γ)).
215
+ - `n_prototypes_`, `compression_ratio_` — Compressed reference set size and fraction of training rows kept.
216
+ - `selected_params_` — Final active hyperparameters (either fixed or chosen by `auto_tune=True`).
217
+ - `tuning_info_` — Validation Macro-F1, p95 latency, p95 ratio, representative count, and tuning time in ms (when `auto_tune=True`).
218
+
219
+ ---
220
+
221
+ ## When to Use LAMP-KNN
222
+
223
+ - **Best fit:** Binary imbalanced tabular datasets with ***N* ≥ 1,000**, **IR ≥ 10**, or ***d* ≥ 20**, where single-row latency matters alongside Macro-F1 and Minority-F1.
224
+ - **Caveats:**
225
+ - On very small datasets (*N* < 500) full `cKDTree` search is already near the ~10 µs Python call floor, so relative 20% latency savings may not be physically attainable.
226
+ - On tiny discrete/binary feature spaces with extreme duplicate vectors (very few unique vectors), try smaller `voronoi_beta` (e.g., `0.0` or `0.5`).
227
+ - On ultra-sparse high-dimensional minority pockets, prefer `evidence_neighbors=0`.
228
+
229
+ ---
230
+
231
+ ## License
232
+
233
+ Released under the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,199 @@
1
+ # LAMP-KNN
2
+
3
+ **Latency-Aware Majority Prototype Selection for Imbalanced Tabular KNN**
4
+
5
+ [![Python](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://pypi.org/project/lamp-knn/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ `lamp-knn` is a lightweight, **scikit-learn compatible** Python library implementing **LAMP-KNN**, a prototype-selection *K-Nearest Neighbors* classifier specifically designed for **binary imbalanced tabular data** under strict single-row inference latency budgets.
9
+
10
+ Unlike naive majority undersampling (which discards majority observations without compensating density distortion and suffers class inversion on low-imbalance datasets), LAMP-KNN combines four mathematical mechanisms:
11
+
12
+ 1. **Continuous Margin Boundary Ranking & Interior Clustering** — Ranks majority candidates by `(-minority_neighbor_count, dist_to_nearest_minority)` in round-robin order per minority point (eliminating zero-boundary starvation on separated or high-dimensional data) and fills the remaining quota from K-means interior clusters while retaining **100% of minority training samples**.
13
+ 2. **Exact Voronoi Mass Conservation** — Assigns each retained majority prototype *p*ⱼ ∈ *S*₀ its exact Voronoi cell mass *m*ⱼ (Σ *m*ⱼ = *N*₀), preserving full-dataset majority density at any compression ratio and preventing class inversion.
14
+ 3. **Full-Data Cached Local Posterior Evidence** — Computes Laplace-smoothed local minority posterior evidence *e*ᵢ on the full training set *prior* to majority pruning so retained prototypes preserve neighborhood purity.
15
+ 4. **Bayesian Prior-Calibrated Signed-Evidence Inference** — Precomputes signed prototype evidence *v*ᵢ = *m*ᵢ^β (*e*ᵢ − τ(γ)) with prior threshold τ(γ) = *r*\_π^γ / (1 + *r*\_π^γ) offline, reducing single-row prediction to **one compressed `cKDTree` query and one NumPy dot product** with direct NumPy standardization (avoiding scikit-learn's ~40 µs single-row `StandardScaler.transform` wrapper overhead).
16
+
17
+ ---
18
+
19
+ ## Empirical Highlights (20 Independent KEEL Datasets, 100 Folds)
20
+
21
+ Under independent latency-constrained tuning (`p95 <= 0.80 * standard KNN`, identical direct NumPy standardization, 3 interleaved test timing sessions):
22
+
23
+ | Method | Mean Macro-F1 (Rank) | Mean Minority-F1 | Mean Bal. Acc. | Mean p95 Latency (µs) | 3-Session Target Attainment | Median Total Break-Even (Queries) |
24
+ |---|---:|---:|---:|---:|---:|---:|
25
+ | **LAMP-KNN** | **0.814 (#1)** | **0.681 (#1)** | 0.833 (#2) | **13.15 (#1)** | **65 / 100** | **88,469** |
26
+ | KNN-BPP (full ref.) | 0.812 (#3) | 0.680 (#2) | 0.847 (#1) | 27.68 (#6) | — | — |
27
+ | CABLE-kNN (full ref.) | 0.810 (#2) | 0.666 (#3) | 0.818 (#4) | 30.37 (#7) | — | — |
28
+ | Standard KNN (full ref.) | 0.791 (#4) | 0.622 (#5) | 0.785 (#7) | 29.59 (#5) | — | — |
29
+ | Random undersampling | 0.773 (#5) | 0.646 (#4) | 0.823 (#3) | 16.56 (#2) | 52 / 100 | 91,457 |
30
+ | CIS multi-cluster | 0.771 (#6) | 0.645 (#5) | 0.816 (#5) | 16.68 (#3) | 47 / 100 | 433,974 |
31
+ | NearMiss-3 | 0.745 (#7) | 0.618 (#7) | 0.786 (#6) | 16.93 (#4) | 44 / 100 | 94,554 |
32
+
33
+ - **Statistically significant Macro-F1 wins** (Friedman χ² = 14.585, *p* = 0.0238; Holm-corrected Wilcoxon): outperforms **NearMiss-3** (*p*\_Holm = 0.0032), **CIS multi-cluster** (*p*\_Holm = 0.0145), and **Random undersampling** (*p*\_Holm = 0.0356).
34
+ - **Statistically significant p95 latency wins against all 6 baselines** (*p*\_Holm ≤ 0.0100; 20/20 wins over full-reference KNN, KNN-BPP, and CABLE-kNN at *p*\_Holm = 1.14 × 10⁻⁵).
35
+ - **Strong out-of-panel generalization:** On 6 untouched KEEL datasets, frozen LAMP-KNN again ranks **#1 on Macro-F1**, **#1 on Minority-F1**, and **#1 fastest on single-row p95 latency** (`12.45 µs`).
36
+
37
+ ---
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ pip install lamp-knn
43
+ ```
44
+
45
+ Requires Python `>= 3.9`, `numpy >= 1.23`, `scipy >= 1.10`, and `scikit-learn >= 1.2`.
46
+
47
+ ---
48
+
49
+ ## Quickstart
50
+
51
+ ### 1. Drop-In Scikit-Learn Usage (Fast Fixed-Parameter Mode)
52
+
53
+ ```python
54
+ from sklearn.datasets import make_classification
55
+ from sklearn.metrics import classification_report, f1_score
56
+ from sklearn.model_selection import train_test_split
57
+ from lamp_knn import LampKNNClassifier
58
+
59
+ X, y = make_classification(
60
+ n_samples=3000,
61
+ n_features=20,
62
+ n_informative=10,
63
+ weights=[0.95, 0.05],
64
+ random_state=42,
65
+ )
66
+ X_train, X_test, y_train, y_test = train_test_split(
67
+ X, y, test_size=0.2, stratify=y, random_state=42
68
+ )
69
+
70
+ clf = LampKNNClassifier(
71
+ n_neighbors=5,
72
+ majority_fraction=0.25, # keep 25% of majority + 100% of minority
73
+ boundary_fraction=0.50,
74
+ voronoi_beta=1.0, # exact Voronoi mass conservation
75
+ prior_gamma=0.5, # Bayesian prior calibration
76
+ evidence_neighbors=0, # 0 for exact labels, or 3/7 for noisy overlap
77
+ standardize=True, # built-in direct NumPy z-score standardization
78
+ random_state=42,
79
+ )
80
+ clf.fit(X_train, y_train)
81
+
82
+ y_pred = clf.predict(X_test)
83
+ print(f"Macro-F1: {f1_score(y_test, y_pred, average='macro'):.4f}")
84
+ print(f"Prototypes kept: {clf.n_prototypes_} / {len(X_train)} ({clf.compression_ratio_:.1%})")
85
+ print(classification_report(y_test, y_pred))
86
+ ```
87
+
88
+ ### 2. Automatic Latency-Constrained Tuning (`auto_tune=True`)
89
+
90
+ Use `auto_tune=True` to run the full latency-constrained protocol from the paper: vectorized NumPy quality selection over all 72 scoring rules per `(budget, boundary_fraction, k)`, followed by 3-session interleaved p95 latency profiling on at most 16 `(budget, k)` representatives subject to `p95 <= latency_ratio * full_knn_p95`.
91
+
92
+ ```python
93
+ from lamp_knn import LampKNNClassifier
94
+
95
+ clf = LampKNNClassifier(
96
+ auto_tune=True,
97
+ latency_ratio=0.80, # target p95 <= 80% of standard full-reference KNN
98
+ standardize=True,
99
+ random_state=42,
100
+ )
101
+ clf.fit(X_train, y_train)
102
+
103
+ print("Selected hyperparameters:", clf.selected_params_)
104
+ print("Validation tuning summary:", clf.tuning_info_)
105
+ y_pred = clf.predict(X_test)
106
+ ```
107
+
108
+ ### 3. Ultra-Fast Single-Row Inference (`predict_one`)
109
+
110
+ For low-latency online serving (e.g., fraud or anomaly scoring one event at a time), call `predict_one(x)` to bypass 2D batch validation overhead and execute direct NumPy standardization + compressed `cKDTree` query + dot product:
111
+
112
+ ```python
113
+ single_event = X_test[0] # 1D NumPy array of shape (n_features,)
114
+ label = clf.predict_one(single_event)
115
+ ```
116
+
117
+ > **Performance tip:** Keep `standardize=True` inside `LampKNNClassifier` instead of wrapping it after `sklearn.preprocessing.StandardScaler` in single-row loops. Calling `StandardScaler.transform(x[None, :])` per row adds ~40 µs of Python validation overhead, whereas built-in NumPy standardization adds only ~0.6–0.8 µs.
118
+
119
+ ### 4. Probabilities, Decision Scores, Arbitrary Labels & Cross-Validation
120
+
121
+ `LampKNNClassifier` works with arbitrary binary labels (e.g., `["legit", "fraud"]` or `[-1, 1]`), automatically identifies the minority class, and supports `decision_function`, `predict_proba`, `cross_val_score`, `GridSearchCV`, and `Pipeline`:
122
+
123
+ ```python
124
+ from sklearn.metrics import average_precision_score, roc_auc_score
125
+ from sklearn.model_selection import StratifiedKFold, cross_val_score
126
+
127
+ scores = clf.decision_function(X_test)
128
+ probas = clf.predict_proba(X_test)[:, 1]
129
+ print("ROC-AUC:", roc_auc_score(y_test, scores))
130
+ print("PR-AUC: ", average_precision_score(y_test, probas))
131
+
132
+ cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
133
+ f1_cv = cross_val_score(
134
+ LampKNNClassifier(majority_fraction=0.25, prior_gamma=0.5, random_state=42),
135
+ X, y, cv=cv, scoring="f1_macro",
136
+ )
137
+ print(f"5-fold Macro-F1: {f1_cv.mean():.4f} +/- {f1_cv.std():.4f}")
138
+ ```
139
+
140
+ ### 5. Low-Level Prototype Selection API (`LampPrototypeSelector`)
141
+
142
+ If you want to inspect or reuse the selected prototypes, exact Voronoi masses, or full-data cached local evidence directly:
143
+
144
+ ```python
145
+ import numpy as np
146
+ from lamp_knn import LampPrototypeSelector
147
+
148
+ # Assumes X_scaled is standardized and y_bin is encoded as 0 (majority) / 1 (minority)
149
+ selector = LampPrototypeSelector(X_scaled, y_bin, neighborhood_size=11, random_state=42)
150
+ rows, masses = selector.select_with_voronoi_mass(majority_budget=300, boundary_fraction=0.5)
151
+ evidence = selector.local_evidence(h_ev=7, alpha=1.0)[rows]
152
+
153
+ assert np.isclose(masses[y_bin[rows] == 0].sum(), np.count_nonzero(y_bin == 0))
154
+ ```
155
+
156
+ ---
157
+
158
+ ## Key Parameters & Practical Guidance
159
+
160
+ | Parameter | Default | Description & Recommended Usage |
161
+ |---|---:|---|
162
+ | `n_neighbors` | `5` | Number of nearest prototype neighbors *k* (`auto_tune=False`). |
163
+ | `majority_fraction` | `0.25` | Share of majority rows kept (`0.10–0.50` for *N* ≥ 1,000 or *d* ≥ 20). |
164
+ | `boundary_fraction` | `0.5` | Share of majority budget allocated to continuous margin boundary points. |
165
+ | `voronoi_beta` | `1.0` | Voronoi mass exponent β ≥ 0 (`1.0` prevents class inversion on low-IR data; `0.5` softens extreme masses). |
166
+ | `prior_gamma` | `0.5` | Prior threshold exponent γ ∈ [0, 1] (`0.0` favors precision/standard posterior; `0.5–0.75` maximizes Macro-F1; `1.0` maximizes G-mean/Balanced Accuracy). |
167
+ | `evidence_neighbors` | `0` | Full-data cached local evidence *h*\_ev (`0` safest on ultra-sparse high-dimensional data; `3` or `7` helpful on noisy overlapping regimes). |
168
+ | `rank_rho` | `0.0` | Neighbor rank weighting (`0.0` uniform; `1.0` inverse-rank `1/r`). |
169
+ | `standardize` | `True` | Built-in direct NumPy z-score standardization `(x - mean_) / scale_`. |
170
+ | `auto_tune` | `False` | Enables internal validation search + 3-session p95 latency selection over ≤ 16 representatives. |
171
+ | `latency_ratio` | `0.80` | Maximum allowed validation p95 ratio vs. full-reference KNN when `auto_tune=True`. |
172
+
173
+ ### Fitted Attributes
174
+
175
+ After calling `fit(X, y)`:
176
+
177
+ - `classes_`, `majority_class_`, `minority_class_` — Detected binary classes.
178
+ - `prototype_indices_` — Row indices of retained prototypes (all minority rows + selected majority prototypes).
179
+ - `voronoi_masses_` — Exact Voronoi mass assigned to each prototype.
180
+ - `signed_values_` — Precomputed signed-evidence vector *v*ᵢ = *m*ᵢ^β (*e*ᵢ − τ(γ)).
181
+ - `n_prototypes_`, `compression_ratio_` — Compressed reference set size and fraction of training rows kept.
182
+ - `selected_params_` — Final active hyperparameters (either fixed or chosen by `auto_tune=True`).
183
+ - `tuning_info_` — Validation Macro-F1, p95 latency, p95 ratio, representative count, and tuning time in ms (when `auto_tune=True`).
184
+
185
+ ---
186
+
187
+ ## When to Use LAMP-KNN
188
+
189
+ - **Best fit:** Binary imbalanced tabular datasets with ***N* ≥ 1,000**, **IR ≥ 10**, or ***d* ≥ 20**, where single-row latency matters alongside Macro-F1 and Minority-F1.
190
+ - **Caveats:**
191
+ - On very small datasets (*N* < 500) full `cKDTree` search is already near the ~10 µs Python call floor, so relative 20% latency savings may not be physically attainable.
192
+ - On tiny discrete/binary feature spaces with extreme duplicate vectors (very few unique vectors), try smaller `voronoi_beta` (e.g., `0.0` or `0.5`).
193
+ - On ultra-sparse high-dimensional minority pockets, prefer `evidence_neighbors=0`.
194
+
195
+ ---
196
+
197
+ ## License
198
+
199
+ Released under the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,68 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lamp-knn"
7
+ version = "0.1.0"
8
+ description = "Latency-Aware Majority Prototype Selection for KNN with Voronoi mass conservation and Bayesian prior calibration on imbalanced tabular data."
9
+ readme = { file = "README.md", content-type = "text/markdown" }
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [
13
+ { name = "kodetr", email = "t4nwi12@gmail.com" },
14
+ ]
15
+ requires-python = ">=3.9"
16
+ keywords = [
17
+ "knn",
18
+ "k-nearest-neighbors",
19
+ "imbalanced-learning",
20
+ "prototype-selection",
21
+ "voronoi",
22
+ "latency-aware",
23
+ "tabular-classification",
24
+ "scikit-learn",
25
+ ]
26
+ classifiers = [
27
+ "Development Status :: 4 - Beta",
28
+ "Intended Audience :: Science/Research",
29
+ "Intended Audience :: Developers",
30
+ "Operating System :: OS Independent",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3.9",
33
+ "Programming Language :: Python :: 3.10",
34
+ "Programming Language :: Python :: 3.11",
35
+ "Programming Language :: Python :: 3.12",
36
+ "Programming Language :: Python :: 3.13",
37
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
38
+ "Topic :: Scientific/Engineering :: Information Analysis",
39
+ "Typing :: Typed",
40
+ ]
41
+ dependencies = [
42
+ "numpy>=1.23",
43
+ "scipy>=1.10",
44
+ "scikit-learn>=1.2",
45
+ ]
46
+
47
+ [project.optional-dependencies]
48
+ dev = [
49
+ "pytest>=7.0",
50
+ "build>=1.0",
51
+ "twine>=5.0",
52
+ ]
53
+
54
+ [project.urls]
55
+ Homepage = "https://pypi.org/project/lamp-knn/"
56
+ Documentation = "https://pypi.org/project/lamp-knn/"
57
+
58
+ [tool.setuptools]
59
+ package-dir = { "" = "src" }
60
+
61
+ [tool.setuptools.packages.find]
62
+ where = ["src"]
63
+
64
+ [tool.setuptools.package-data]
65
+ lamp_knn = ["py.typed"]
66
+
67
+ [tool.pytest.ini_options]
68
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,13 @@
1
+ """LAMP-KNN: Latency-Aware Majority Prototype Selection for Imbalanced Tabular KNN."""
2
+
3
+ from ._estimator import LampKNNClassifier
4
+ from ._prototype import LampPrototypeSelector, vectorized_macro_f1_gmean
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = [
9
+ "LampKNNClassifier",
10
+ "LampPrototypeSelector",
11
+ "vectorized_macro_f1_gmean",
12
+ "__version__",
13
+ ]