vgsp-ml 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.
- vgsp_ml-0.1.0/LICENSE +201 -0
- vgsp_ml-0.1.0/PKG-INFO +142 -0
- vgsp_ml-0.1.0/PYPI_README.md +115 -0
- vgsp_ml-0.1.0/README.md +119 -0
- vgsp_ml-0.1.0/pyproject.toml +38 -0
- vgsp_ml-0.1.0/setup.cfg +4 -0
- vgsp_ml-0.1.0/src/vgsp/__init__.py +6 -0
- vgsp_ml-0.1.0/src/vgsp/_vgsp.py +217 -0
- vgsp_ml-0.1.0/src/vgsp_ml.egg-info/PKG-INFO +142 -0
- vgsp_ml-0.1.0/src/vgsp_ml.egg-info/SOURCES.txt +12 -0
- vgsp_ml-0.1.0/src/vgsp_ml.egg-info/dependency_links.txt +1 -0
- vgsp_ml-0.1.0/src/vgsp_ml.egg-info/requires.txt +8 -0
- vgsp_ml-0.1.0/src/vgsp_ml.egg-info/top_level.txt +1 -0
- vgsp_ml-0.1.0/tests/test_vgsp.py +112 -0
vgsp_ml-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
vgsp_ml-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vgsp-ml
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Supervised variance-guided scalar projection using bounded class-variance ratios
|
|
5
|
+
Author: Mohd Adil Mokti
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/nqmn/vgsp
|
|
8
|
+
Project-URL: Source, https://github.com/nqmn/vgsp
|
|
9
|
+
Project-URL: Issues, https://github.com/nqmn/vgsp/issues
|
|
10
|
+
Project-URL: Research-archive, https://doi.org/10.5281/zenodo.24183611
|
|
11
|
+
Keywords: VGSP,CVR,supervised dimensionality reduction,SDN,DDoS,machine learning
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: numpy>=1.24
|
|
20
|
+
Requires-Dist: scikit-learn<2,>=1.6
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
23
|
+
Requires-Dist: pandas>=2; extra == "dev"
|
|
24
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
25
|
+
Requires-Dist: twine>=6; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# VGSP — Variance-Guided Scalar Projection
|
|
29
|
+
|
|
30
|
+
A `scikit-learn`-compatible **supervised** transformer that maps numeric feature vectors onto one scalar axis using **bounded class-variance ratio (CVR)** weights.
|
|
31
|
+
|
|
32
|
+
This implementation follows `vgspv4.ipynb` (Cell 4) and its training-only imputation, variance filtering and min–max scaling. It is **not** a pretrained DDoS detector and it does not fetch any network data.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
**Before PyPI publication**, clone `https://github.com/nqmn/vgsp` and install:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
python -m pip install -e ".[dev]"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
**After successful PyPI publication:**
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
python -m pip install vgsp-ml
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The distribution name is `vgsp-ml`; the Python import name is `vgsp`.
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from vgsp import VGSP
|
|
54
|
+
from sklearn.model_selection import train_test_split
|
|
55
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
56
|
+
from sklearn.pipeline import Pipeline
|
|
57
|
+
|
|
58
|
+
# X: numeric features only; y: labels for two classes
|
|
59
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
60
|
+
X, y, test_size=0.20, stratify=y, random_state=42
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
model = Pipeline([
|
|
64
|
+
("vgsp", VGSP(n_features=7)),
|
|
65
|
+
("classifier", DecisionTreeClassifier(random_state=42)),
|
|
66
|
+
])
|
|
67
|
+
model.fit(X_train, y_train)
|
|
68
|
+
print(model.score(X_test, y_test))
|
|
69
|
+
print(model.named_steps["vgsp"].selected_input_indices_)
|
|
70
|
+
print(model.named_steps["vgsp"].weights_)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Or use it directly like a `scikit-learn` transformer:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
vgsp = VGSP(n_features=7)
|
|
77
|
+
Z_train = vgsp.fit_transform(X_train, y_train) # shape: (n_train, 1)
|
|
78
|
+
Z_test = vgsp.transform(X_test) # shape: (n_test, 1)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
VGSP **requires labels in `fit`**; unlike PCA it is supervised. `transform` does not accept labels and never refits.
|
|
82
|
+
|
|
83
|
+
## Mathematical definition (binary labels)
|
|
84
|
+
|
|
85
|
+
For feature `j`, with class prior probabilities `p0` and `p1`, class-wise means `mu0,j` and `mu1,j`, and population variances `v0,j` and `v1,j`:
|
|
86
|
+
|
|
87
|
+
- `W_j = p0*v0,j + p1*v1,j`
|
|
88
|
+
- `B_j = p0*p1*(mu0,j-mu1,j)^2`
|
|
89
|
+
- `CVR_j = B_j/(B_j+W_j+epsilon)`
|
|
90
|
+
- `S_k = indices of the largest k CVR values (stable ties)`
|
|
91
|
+
- `w_j = CVR_j/(sum_{i in S_k} CVR_i+epsilon)`
|
|
92
|
+
- `z = X_scaled[:, S_k] @ w`
|
|
93
|
+
|
|
94
|
+
`epsilon` defaults to `1e-10`, and variance is the population variance (`ddof=0`).
|
|
95
|
+
|
|
96
|
+
The bounded CVR criterion is related monotonically to the Fisher score, rather than a claim of an entirely new mathematical separability measure. The research contribution is the CVR-weighted scalar projection mechanism.
|
|
97
|
+
|
|
98
|
+
## What is included inside the transformer
|
|
99
|
+
|
|
100
|
+
Each `VGSP.fit(X_train, y_train)` performs the following operations using **training data only**:
|
|
101
|
+
|
|
102
|
+
1. Converts positive/negative infinity to missing values and applies **median imputation** (`SimpleImputer(keep_empty_features=True)`).
|
|
103
|
+
2. Removes constant columns (`VarianceThreshold(0.0)`).
|
|
104
|
+
3. Learns the **MinMaxScaler**.
|
|
105
|
+
4. Computes **CVR**, ranks features, and freezes `k` indices and weights.
|
|
106
|
+
|
|
107
|
+
`VGSP.transform(X_valid_or_test)` applies the same fitted imputer, variance filter, scaler and projection weights without recomputing CVR. With a scikit-learn `Pipeline`, these stages are refitted only to each CV training fold.
|
|
108
|
+
|
|
109
|
+
## Evaluation protocol preserved from notebook v4
|
|
110
|
+
|
|
111
|
+
The research notebook uses a **stratified 80:20 split** and **five-fold `StratifiedKFold` on the 80% development portion**. The choice `n_features=7` reflects the latest InSDN development selection. This library **does not automatically tune k**; tuning and final evaluation stay outside the transformer and must never involve the 20% test set.
|
|
112
|
+
|
|
113
|
+
For the additional DDOSDN2025 evaluation that fixes the **same seven feature names from InSDN**, explicitly pass `X[FIXED_FEATURE_NAMES]` for that comparison. By default, `VGSP` ranks features locally within the data passed to `fit`; it does **not** claim that selected feature identities transfer between datasets automatically.
|
|
114
|
+
|
|
115
|
+
## Scope and limitations
|
|
116
|
+
|
|
117
|
+
- Binary supervised projection only, for numeric tabular features.
|
|
118
|
+
- `Protocol` coded numerically is a methodological assumption in the supplied research; this package does not imply ordinal meaning is generally appropriate.
|
|
119
|
+
- A scalar representation is not invertible; no `inverse_transform` is defined.
|
|
120
|
+
- A single scalar downstream input does not mean upstream data capture or flow feature-extraction cost disappears.
|
|
121
|
+
- The dataset is not bundled into the package; no DDoS training/evaluation results are guaranteed on other data.
|
|
122
|
+
|
|
123
|
+
## Development and testing
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
python -m pip install -e ".[dev]"
|
|
127
|
+
python -m pytest -q
|
|
128
|
+
python examples/basic_usage.py
|
|
129
|
+
python -m build
|
|
130
|
+
python -m twine check dist/*
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Publication checklist
|
|
134
|
+
|
|
135
|
+
1. Confirm the distribution name `vgsp-ml` is available on PyPI (or choose another) and ensure it is not confused with `PyGSP`, which is an existing *graph signal processing* package.
|
|
136
|
+
2. Preserve the existing Apache-2.0 `LICENSE` already in the repository.
|
|
137
|
+
3. Confirm the source code and PyPI metadata refer to `https://github.com/nqmn/vgsp`.
|
|
138
|
+
4. Run tests and build the distributions.
|
|
139
|
+
5. Trial-publish to TestPyPI, then publish to PyPI using a verified project and preferably GitHub Actions Trusted Publishing.
|
|
140
|
+
6. An earlier research notebook snapshot already has a Zenodo DOI: https://doi.org/10.5281/zenodo.24183611. If citing this newly packaged release, archive its exact source version separately and verify the new version DOI. PyPI alone does not assign DOIs.
|
|
141
|
+
|
|
142
|
+
The manuscript and notebook are research references; confirm the final manuscript and published implementation are aligned before public release.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# VGSP — Variance-Guided Scalar Projection
|
|
2
|
+
|
|
3
|
+
A `scikit-learn`-compatible **supervised** transformer that maps numeric feature vectors onto one scalar axis using **bounded class-variance ratio (CVR)** weights.
|
|
4
|
+
|
|
5
|
+
This implementation follows `vgspv4.ipynb` (Cell 4) and its training-only imputation, variance filtering and min–max scaling. It is **not** a pretrained DDoS detector and it does not fetch any network data.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
**Before PyPI publication**, clone `https://github.com/nqmn/vgsp` and install:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
python -m pip install -e ".[dev]"
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
**After successful PyPI publication:**
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
python -m pip install vgsp-ml
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The distribution name is `vgsp-ml`; the Python import name is `vgsp`.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from vgsp import VGSP
|
|
27
|
+
from sklearn.model_selection import train_test_split
|
|
28
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
29
|
+
from sklearn.pipeline import Pipeline
|
|
30
|
+
|
|
31
|
+
# X: numeric features only; y: labels for two classes
|
|
32
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
33
|
+
X, y, test_size=0.20, stratify=y, random_state=42
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
model = Pipeline([
|
|
37
|
+
("vgsp", VGSP(n_features=7)),
|
|
38
|
+
("classifier", DecisionTreeClassifier(random_state=42)),
|
|
39
|
+
])
|
|
40
|
+
model.fit(X_train, y_train)
|
|
41
|
+
print(model.score(X_test, y_test))
|
|
42
|
+
print(model.named_steps["vgsp"].selected_input_indices_)
|
|
43
|
+
print(model.named_steps["vgsp"].weights_)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Or use it directly like a `scikit-learn` transformer:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
vgsp = VGSP(n_features=7)
|
|
50
|
+
Z_train = vgsp.fit_transform(X_train, y_train) # shape: (n_train, 1)
|
|
51
|
+
Z_test = vgsp.transform(X_test) # shape: (n_test, 1)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
VGSP **requires labels in `fit`**; unlike PCA it is supervised. `transform` does not accept labels and never refits.
|
|
55
|
+
|
|
56
|
+
## Mathematical definition (binary labels)
|
|
57
|
+
|
|
58
|
+
For feature `j`, with class prior probabilities `p0` and `p1`, class-wise means `mu0,j` and `mu1,j`, and population variances `v0,j` and `v1,j`:
|
|
59
|
+
|
|
60
|
+
- `W_j = p0*v0,j + p1*v1,j`
|
|
61
|
+
- `B_j = p0*p1*(mu0,j-mu1,j)^2`
|
|
62
|
+
- `CVR_j = B_j/(B_j+W_j+epsilon)`
|
|
63
|
+
- `S_k = indices of the largest k CVR values (stable ties)`
|
|
64
|
+
- `w_j = CVR_j/(sum_{i in S_k} CVR_i+epsilon)`
|
|
65
|
+
- `z = X_scaled[:, S_k] @ w`
|
|
66
|
+
|
|
67
|
+
`epsilon` defaults to `1e-10`, and variance is the population variance (`ddof=0`).
|
|
68
|
+
|
|
69
|
+
The bounded CVR criterion is related monotonically to the Fisher score, rather than a claim of an entirely new mathematical separability measure. The research contribution is the CVR-weighted scalar projection mechanism.
|
|
70
|
+
|
|
71
|
+
## What is included inside the transformer
|
|
72
|
+
|
|
73
|
+
Each `VGSP.fit(X_train, y_train)` performs the following operations using **training data only**:
|
|
74
|
+
|
|
75
|
+
1. Converts positive/negative infinity to missing values and applies **median imputation** (`SimpleImputer(keep_empty_features=True)`).
|
|
76
|
+
2. Removes constant columns (`VarianceThreshold(0.0)`).
|
|
77
|
+
3. Learns the **MinMaxScaler**.
|
|
78
|
+
4. Computes **CVR**, ranks features, and freezes `k` indices and weights.
|
|
79
|
+
|
|
80
|
+
`VGSP.transform(X_valid_or_test)` applies the same fitted imputer, variance filter, scaler and projection weights without recomputing CVR. With a scikit-learn `Pipeline`, these stages are refitted only to each CV training fold.
|
|
81
|
+
|
|
82
|
+
## Evaluation protocol preserved from notebook v4
|
|
83
|
+
|
|
84
|
+
The research notebook uses a **stratified 80:20 split** and **five-fold `StratifiedKFold` on the 80% development portion**. The choice `n_features=7` reflects the latest InSDN development selection. This library **does not automatically tune k**; tuning and final evaluation stay outside the transformer and must never involve the 20% test set.
|
|
85
|
+
|
|
86
|
+
For the additional DDOSDN2025 evaluation that fixes the **same seven feature names from InSDN**, explicitly pass `X[FIXED_FEATURE_NAMES]` for that comparison. By default, `VGSP` ranks features locally within the data passed to `fit`; it does **not** claim that selected feature identities transfer between datasets automatically.
|
|
87
|
+
|
|
88
|
+
## Scope and limitations
|
|
89
|
+
|
|
90
|
+
- Binary supervised projection only, for numeric tabular features.
|
|
91
|
+
- `Protocol` coded numerically is a methodological assumption in the supplied research; this package does not imply ordinal meaning is generally appropriate.
|
|
92
|
+
- A scalar representation is not invertible; no `inverse_transform` is defined.
|
|
93
|
+
- A single scalar downstream input does not mean upstream data capture or flow feature-extraction cost disappears.
|
|
94
|
+
- The dataset is not bundled into the package; no DDoS training/evaluation results are guaranteed on other data.
|
|
95
|
+
|
|
96
|
+
## Development and testing
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
python -m pip install -e ".[dev]"
|
|
100
|
+
python -m pytest -q
|
|
101
|
+
python examples/basic_usage.py
|
|
102
|
+
python -m build
|
|
103
|
+
python -m twine check dist/*
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Publication checklist
|
|
107
|
+
|
|
108
|
+
1. Confirm the distribution name `vgsp-ml` is available on PyPI (or choose another) and ensure it is not confused with `PyGSP`, which is an existing *graph signal processing* package.
|
|
109
|
+
2. Preserve the existing Apache-2.0 `LICENSE` already in the repository.
|
|
110
|
+
3. Confirm the source code and PyPI metadata refer to `https://github.com/nqmn/vgsp`.
|
|
111
|
+
4. Run tests and build the distributions.
|
|
112
|
+
5. Trial-publish to TestPyPI, then publish to PyPI using a verified project and preferably GitHub Actions Trusted Publishing.
|
|
113
|
+
6. An earlier research notebook snapshot already has a Zenodo DOI: https://doi.org/10.5281/zenodo.24183611. If citing this newly packaged release, archive its exact source version separately and verify the new version DOI. PyPI alone does not assign DOIs.
|
|
114
|
+
|
|
115
|
+
The manuscript and notebook are research references; confirm the final manuscript and published implementation are aligned before public release.
|
vgsp_ml-0.1.0/README.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# Variance-Guided Scalar Projection (VGSP)
|
|
2
|
+
|
|
3
|
+
**Python implementation for lightweight DDoS detection in Software-Defined Networks**
|
|
4
|
+
|
|
5
|
+
[](https://doi.org/10.5281/zenodo.24183611)
|
|
6
|
+
|
|
7
|
+
This repository contains `vgspv4.ipynb`, a Jupyter Notebook implementing **Variance-Guided Scalar Projection (VGSP)** for binary classification of normal and Distributed Denial-of-Service (DDoS) traffic in Software-Defined Networks (SDN). The notebook accompanies the research manuscript *A Variance-Guided Scalar Traffic Representation for Lightweight DDoS Detection in Software-Defined Networks*.
|
|
8
|
+
|
|
9
|
+
VGSP derives feature weights using a bounded **Class-Variance Ratio (CVR)** criterion and projects multiple traffic features onto a **single scalar representation** before classification. The research contribution is the CVR-guided scalar projection workflow, rather than treating the bounded CVR transformation in isolation as a new general-purpose separability metric.
|
|
10
|
+
|
|
11
|
+
## Research code and archive
|
|
12
|
+
|
|
13
|
+
- **Notebook:** [`vgspv4.ipynb`](vgspv4.ipynb)
|
|
14
|
+
- **Archived software DOI (Zenodo):** https://doi.org/10.5281/zenodo.24183611
|
|
15
|
+
- **Version represented here:** v4 (notebook last-update note: 13 November 2026)
|
|
16
|
+
- **Implementation:** Python / Jupyter Notebook
|
|
17
|
+
|
|
18
|
+
For scholarly citations, cite the version archived on **Zenodo** using the DOI above. The GitHub repository is intended for code access and future development; a subsequently updated GitHub file may differ from the archived Zenodo version.
|
|
19
|
+
|
|
20
|
+
## Method overview
|
|
21
|
+
|
|
22
|
+
For each feature \(j\), the implementation calculates within-class variance \(W_j\) and between-class variance \(B_j\), then computes
|
|
23
|
+
|
|
24
|
+
\[
|
|
25
|
+
\operatorname{CVR}(j)=\frac{B_j}{B_j+W_j+\varepsilon}, \qquad \varepsilon=10^{-10}.
|
|
26
|
+
\]
|
|
27
|
+
|
|
28
|
+
The highest-ranked features receive CVR-proportional projection weights. Their weighted combination produces a one-dimensional scalar \(z\), which is passed to a machine-learning classifier.
|
|
29
|
+
|
|
30
|
+
The notebook includes:
|
|
31
|
+
|
|
32
|
+
- Binary dataset loading and inspection, with duplicate-vector diagnostics.
|
|
33
|
+
- Stratified **80:20 development/test splitting** and **five-fold `StratifiedKFold`** evaluation.
|
|
34
|
+
- Training-fitted median imputation, zero-variance filtering where applicable, min-max scaling, CVR computation, feature ranking, and scalar projection.
|
|
35
|
+
- Feature-count ablation for **\(k=1,\ldots,12\)** using InSDN development-fold Macro-F1.
|
|
36
|
+
- Sensitivity analyses for `Protocol` encoding and correlated features.
|
|
37
|
+
- Comparisons with full-feature, variance-threshold, Fisher-score, PCA-1D, and LDA-1D baselines.
|
|
38
|
+
- Evaluation with Decision Tree (DT), Random Forest (RF), XGBoost (XGB), and LightGBM (LGBM).
|
|
39
|
+
- Predictive metrics, computational timings, paired Wilcoxon comparisons, visualization, and Decision Tree complexity analysis.
|
|
40
|
+
|
|
41
|
+
### Evaluation scope
|
|
42
|
+
|
|
43
|
+
In the archived v4 notebook, the InSDN development cross-validation selects **seven traffic features**: `Protocol`, `Down/Up Ratio`, `Init Bwd Win Byts`, `Pkt Len Min`, `ACK Flag Cnt`, `Bwd Pkt Len Min`, and `Bwd Pkts/s`. The selected **feature names** are then evaluated on DDOSDN2025 with dataset-specific preprocessing, CVR weights, and classifiers fitted from that dataset's own training partitions. **This is within-dataset evaluation, not a train-on-InSDN/test-on-DDOSDN2025 transfer experiment.**
|
|
44
|
+
|
|
45
|
+
The notebook uses stratified splitting, **not group-aware cross-validation**. Duplicate-vector hashes are calculated for diagnostic purposes; they are not used to create the folds. Fitted preprocessing and VGSP parameters are estimated from the appropriate training partition and applied unchanged to its validation or held-out test partition.
|
|
46
|
+
|
|
47
|
+
## Requirements
|
|
48
|
+
|
|
49
|
+
- Python 3.12 (notebook metadata records Python 3.12.3)
|
|
50
|
+
- JupyterLab or Jupyter Notebook
|
|
51
|
+
- NumPy, pandas, SciPy, scikit-learn, matplotlib, seaborn, XGBoost, LightGBM, joblib, threadpoolctl, and IPython
|
|
52
|
+
|
|
53
|
+
Exact package versions are not pinned in the notebook. For precise environment-level reproduction, record the versions used in your own execution environment.
|
|
54
|
+
|
|
55
|
+
## Datasets and file paths
|
|
56
|
+
|
|
57
|
+
The notebook requires **two previously prepared binary CSV files** (labels: `0` = Normal, `1` = DDoS):
|
|
58
|
+
|
|
59
|
+
| Dataset | Expected CSV filename | Records in notebook | Numeric features used |
|
|
60
|
+
| --- | --- | ---: | ---: |
|
|
61
|
+
| InSDN | `insdn_ddos_binary_0n1d.csv` | 190,366 | 77 |
|
|
62
|
+
| DDOSDN2025 | `ddosdn2025_binary_0n1d.csv` | 200,378 | 77 |
|
|
63
|
+
|
|
64
|
+
**Before running the notebook, check or change `INSDN_PATH` and `DDOSDN_PATH` in the first configuration code cell.** The original settings are:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
INSDN_PATH = Path("../ds/insdn_ddos_binary_0n1d.csv")
|
|
68
|
+
DDOSDN_PATH = Path("../ds/ddosdn2025_binary_0n1d.csv")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
If launching Jupyter from the repository directory, those settings correspond to the following example layout:
|
|
72
|
+
|
|
73
|
+
```text
|
|
74
|
+
workspace/
|
|
75
|
+
├── ds/
|
|
76
|
+
│ ├── insdn_ddos_binary_0n1d.csv
|
|
77
|
+
│ └── ddosdn2025_binary_0n1d.csv
|
|
78
|
+
└── VGSP/
|
|
79
|
+
├── README.md
|
|
80
|
+
└── vgspv4.ipynb
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Alternatively, place the CSV files in a local `data/` directory inside the repository and change the two paths to `Path("data/<filename>.csv")` accordingly. Relative paths are interpreted from **the Jupyter process working directory**, not necessarily from the notebook file's directory.
|
|
84
|
+
|
|
85
|
+
**Important:** The inputs are prepared *binary* CSVs, not necessarily the original raw dataset downloads. This notebook does not itself reconstruct those CSVs from the complete source datasets. Ensure that the files, labels, feature columns, and preprocessing match the research inputs before interpreting results. Data files are separately licensed by their original providers; the software license does not replace dataset licensing terms.
|
|
86
|
+
|
|
87
|
+
Dataset sources:
|
|
88
|
+
|
|
89
|
+
1. **InSDN:** Elsayed, M. S., Le-Khac, N.-A., and Jurcut, A. D. (2020), *InSDN: A Novel SDN Intrusion Dataset*, **IEEE Access**, 8, 165263–165284. https://doi.org/10.1109/ACCESS.2020.3022633
|
|
90
|
+
2. **DDOSDN2025:** Mokti, M. A. (2025), *DDOSDN2025*, Mendeley Data, Version 1. https://doi.org/10.17632/9c5yjbk354.1
|
|
91
|
+
|
|
92
|
+
## Limitations and reproducibility notes
|
|
93
|
+
|
|
94
|
+
- Experiments assess **binary Normal versus DDoS classification** on the specified, prepared datasets.
|
|
95
|
+
- The principal validation protocol is stratified and may not eliminate dependence among records sharing capture sessions, hosts, or identical feature vectors.
|
|
96
|
+
- The reported computational measurements are notebook-based experiments; they do not establish full packet-capture-to-controller operational latency.
|
|
97
|
+
- Results depend on input-data preparation, package versions, hardware, and execution environment. The presence of code in this repository does not by itself guarantee exact numerical reproduction on other systems.
|
|
98
|
+
- The uploaded v4 notebook uses **seven** selected features. Ensure that the associated manuscript, Zenodo version, and GitHub notebook describe the same released experiment.
|
|
99
|
+
|
|
100
|
+
## Citation
|
|
101
|
+
|
|
102
|
+
**Software** (confirm the exact author, title, and version against the published Zenodo citation metadata):
|
|
103
|
+
|
|
104
|
+
> Mokti, M. A. (2026). *Variance-Guided Scalar Projection (VGSP): Python Implementation for Lightweight DDoS Detection in Software-Defined Networks* [Computer software]. Zenodo. https://doi.org/10.5281/zenodo.24183611
|
|
105
|
+
|
|
106
|
+
**Associated manuscript:**
|
|
107
|
+
|
|
108
|
+
> Mokti, M. A., Abu Bakar, K. A., and Zainol Ariffin, K. A. *A Variance-Guided Scalar Traffic Representation for Lightweight DDoS Detection in Software-Defined Networks*. Manuscript under revision; journal DOI not yet included in this repository.
|
|
109
|
+
|
|
110
|
+
Please cite the original InSDN and DDOSDN2025 sources when using those datasets.
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
Use the **same software license** in GitHub and the Zenodo record. If you selected **MIT** in Zenodo, add a `LICENSE` file containing the MIT License text and the appropriate copyright holder(s) to this repository. Dataset licenses remain separate from the code license.
|
|
115
|
+
|
|
116
|
+
## Contact
|
|
117
|
+
|
|
118
|
+
**Mohd Adil Mokti**
|
|
119
|
+
Center for Cyber Security, Faculty of Information Science and Technology, Universiti Kebangsaan Malaysia, Malaysia.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "vgsp-ml"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Supervised variance-guided scalar projection using bounded class-variance ratios"
|
|
9
|
+
readme = "PYPI_README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
authors = [{ name = "Mohd Adil Mokti" }]
|
|
13
|
+
keywords = ["VGSP", "CVR", "supervised dimensionality reduction", "SDN", "DDoS", "machine learning"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Science/Research",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
19
|
+
]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"numpy>=1.24",
|
|
22
|
+
"scikit-learn>=1.6,<2",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/nqmn/vgsp"
|
|
27
|
+
Source = "https://github.com/nqmn/vgsp"
|
|
28
|
+
Issues = "https://github.com/nqmn/vgsp/issues"
|
|
29
|
+
Research-archive = "https://doi.org/10.5281/zenodo.24183611"
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
dev = ["pytest>=8", "pandas>=2", "build>=1.2", "twine>=6"]
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
testpaths = ["tests"]
|
vgsp_ml-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""The variance-guided scalar projection (VGSP) transformer.
|
|
2
|
+
|
|
3
|
+
The CVR calculations and train-only preprocessing follow the research
|
|
4
|
+
implementation supplied in notebook vgspv4.ipynb (Cell 4) and associated
|
|
5
|
+
train-only preprocessing cells. The original model is binary supervised.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
12
|
+
from sklearn.feature_selection import VarianceThreshold
|
|
13
|
+
from sklearn.impute import SimpleImputer
|
|
14
|
+
from sklearn.preprocessing import MinMaxScaler
|
|
15
|
+
from sklearn.utils.validation import (
|
|
16
|
+
check_consistent_length,
|
|
17
|
+
check_is_fitted,
|
|
18
|
+
check_array,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class VGSP(TransformerMixin, BaseEstimator):
|
|
23
|
+
"""Project numeric features onto one CVR-weighted scalar axis.
|
|
24
|
+
|
|
25
|
+
VGSP is a *supervised* dimensionality-reduction transformer. Its fit()
|
|
26
|
+
requires binary labels. Preprocessing (median imputation, removal of
|
|
27
|
+
constant features, and min-max scaling) is learned only from fit(X, y)
|
|
28
|
+
and reused unchanged during transform(X).
|
|
29
|
+
|
|
30
|
+
Parameters
|
|
31
|
+
----------
|
|
32
|
+
n_features : int, default=7
|
|
33
|
+
Number of top-ranked features to use. The research's latest
|
|
34
|
+
validated InSDN configuration chose seven features; this value
|
|
35
|
+
can be changed for other applications.
|
|
36
|
+
epsilon : float, default=1e-10
|
|
37
|
+
Strictly positive numerical stabilizer for CVR and weight sums.
|
|
38
|
+
|
|
39
|
+
Attributes
|
|
40
|
+
----------
|
|
41
|
+
classes_ : ndarray of shape (2,)
|
|
42
|
+
Class labels ordered by np.unique (class mapping is internal).
|
|
43
|
+
cvr_scores_ : ndarray of shape (n_informative_features,)
|
|
44
|
+
CVR scores on the training data, after variance filtering.
|
|
45
|
+
selected_indices_ : ndarray of shape (n_features,)
|
|
46
|
+
Selected column indices after variance filtering.
|
|
47
|
+
selected_input_indices_ : ndarray of shape (n_features,)
|
|
48
|
+
Selected indices referring to the original input columns.
|
|
49
|
+
weights_ : ndarray of shape (n_features,)
|
|
50
|
+
CVR-proportional projection weights.
|
|
51
|
+
selected_feature_names_ : ndarray of shape (n_features,)
|
|
52
|
+
Names when fitted on a pandas DataFrame with string column names.
|
|
53
|
+
|
|
54
|
+
Notes
|
|
55
|
+
-----
|
|
56
|
+
The per-feature CVR and scalar projection use the research equations:
|
|
57
|
+
W = p0*var(X0) + p1*var(X1)
|
|
58
|
+
B = p0*p1*(mean(X0)-mean(X1))**2
|
|
59
|
+
CVR = B/(B+W+epsilon)
|
|
60
|
+
w = CVR_selected/(sum(CVR_selected)+epsilon)
|
|
61
|
+
z = X_scaled_selected @ w
|
|
62
|
+
Population variance is used (numpy default, ddof=0).
|
|
63
|
+
Only binary classification is supported by this research version.
|
|
64
|
+
|
|
65
|
+
Example
|
|
66
|
+
-------
|
|
67
|
+
>>> from vgsp import VGSP
|
|
68
|
+
>>> model = VGSP(n_features=2)
|
|
69
|
+
>>> X = [[1., 4., 0], [2., 5., 2], [6., 7., 3], [7., 8., 5]]
|
|
70
|
+
>>> z = model.fit_transform(X, [0, 0, 1, 1])
|
|
71
|
+
>>> z.shape
|
|
72
|
+
(4, 1)
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(self, n_features: int = 7, epsilon: float = 1e-10):
|
|
76
|
+
self.n_features = n_features
|
|
77
|
+
self.epsilon = epsilon
|
|
78
|
+
|
|
79
|
+
def _validate_input(self, X, *, reset: bool):
|
|
80
|
+
# Preserve DataFrame names after validate_data: converting to an ndarray
|
|
81
|
+
# first makes scikit-learn clear feature_names_in_ during a fit reset.
|
|
82
|
+
pending_names = None
|
|
83
|
+
if hasattr(X, "columns"):
|
|
84
|
+
col_names = list(X.columns)
|
|
85
|
+
if len(set(col_names)) != len(col_names):
|
|
86
|
+
raise ValueError("Input DataFrame has duplicate column names.")
|
|
87
|
+
if all(isinstance(c, str) for c in col_names):
|
|
88
|
+
pending_names = np.asarray(col_names, dtype=object)
|
|
89
|
+
if not reset and hasattr(self, "feature_names_in_") and not np.array_equal(
|
|
90
|
+
self.feature_names_in_, pending_names
|
|
91
|
+
):
|
|
92
|
+
raise ValueError(
|
|
93
|
+
"Input DataFrame columns do not match the training columns "
|
|
94
|
+
"in their original order."
|
|
95
|
+
)
|
|
96
|
+
elif not reset and hasattr(self, "feature_names_in_"):
|
|
97
|
+
raise ValueError("Expected DataFrame with original string columns.")
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
values = np.asarray(X, dtype=np.float64)
|
|
101
|
+
except (TypeError, ValueError) as exc:
|
|
102
|
+
raise ValueError(
|
|
103
|
+
"VGSP requires numeric features. Exclude identifiers and labels first."
|
|
104
|
+
) from exc
|
|
105
|
+
|
|
106
|
+
if values.ndim != 2:
|
|
107
|
+
raise ValueError("VGSP expects a two-dimensional feature matrix.")
|
|
108
|
+
# Notebook Cell 2 replaces +/-infinity by NaN before train-only
|
|
109
|
+
# imputation. Replicate that conversion within the transformer.
|
|
110
|
+
values = np.where(np.isfinite(values), values, np.nan)
|
|
111
|
+
checked = check_array(
|
|
112
|
+
values, dtype=np.float64, ensure_all_finite="allow-nan",
|
|
113
|
+
ensure_min_samples=1,
|
|
114
|
+
)
|
|
115
|
+
if reset:
|
|
116
|
+
self.n_features_in_ = checked.shape[1]
|
|
117
|
+
elif checked.shape[1] != self.n_features_in_:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"Expected {self.n_features_in_} input features, got {checked.shape[1]}."
|
|
120
|
+
)
|
|
121
|
+
if reset and pending_names is not None:
|
|
122
|
+
self.feature_names_in_ = pending_names
|
|
123
|
+
return checked
|
|
124
|
+
|
|
125
|
+
def fit(self, X, y):
|
|
126
|
+
"""Fit train-only preprocessing, class CVR scores and 1-D weights."""
|
|
127
|
+
if isinstance(self.n_features, (bool, np.bool_)) or not isinstance(
|
|
128
|
+
self.n_features, (int, np.integer)
|
|
129
|
+
) or self.n_features < 1:
|
|
130
|
+
raise ValueError("n_features must be a positive integer.")
|
|
131
|
+
if not np.isfinite(self.epsilon) or self.epsilon <= 0:
|
|
132
|
+
raise ValueError("epsilon must be a finite positive number.")
|
|
133
|
+
if y is None:
|
|
134
|
+
raise ValueError("VGSP is supervised: fit(X, y) requires binary labels.")
|
|
135
|
+
|
|
136
|
+
A = self._validate_input(X, reset=True)
|
|
137
|
+
y = np.asarray(y)
|
|
138
|
+
if y.ndim != 1:
|
|
139
|
+
raise ValueError("y must be a one-dimensional binary label vector.")
|
|
140
|
+
check_consistent_length(A, y)
|
|
141
|
+
self.classes_ = np.unique(y)
|
|
142
|
+
if len(self.classes_) != 2:
|
|
143
|
+
raise ValueError("VGSP requires exactly two classes in y.")
|
|
144
|
+
|
|
145
|
+
self.imputer_ = SimpleImputer(
|
|
146
|
+
strategy="median", keep_empty_features=True
|
|
147
|
+
)
|
|
148
|
+
A = self.imputer_.fit_transform(A)
|
|
149
|
+
self.variance_filter_ = VarianceThreshold(threshold=0.0)
|
|
150
|
+
try:
|
|
151
|
+
A = self.variance_filter_.fit_transform(A)
|
|
152
|
+
except ValueError as exc:
|
|
153
|
+
raise ValueError(
|
|
154
|
+
"No non-constant numeric features remain after imputation."
|
|
155
|
+
) from exc
|
|
156
|
+
if self.n_features > A.shape[1]:
|
|
157
|
+
raise ValueError(
|
|
158
|
+
f"n_features={self.n_features} exceeds the {A.shape[1]} "
|
|
159
|
+
"non-constant training features."
|
|
160
|
+
)
|
|
161
|
+
self.scaler_ = MinMaxScaler()
|
|
162
|
+
A = self.scaler_.fit_transform(A)
|
|
163
|
+
|
|
164
|
+
X0 = A[y == self.classes_[0]]
|
|
165
|
+
X1 = A[y == self.classes_[1]]
|
|
166
|
+
p0 = X0.shape[0] / A.shape[0]
|
|
167
|
+
p1 = X1.shape[0] / A.shape[0]
|
|
168
|
+
within = p0 * X0.var(axis=0) + p1 * X1.var(axis=0)
|
|
169
|
+
between = p0 * p1 * (X0.mean(axis=0) - X1.mean(axis=0)) ** 2
|
|
170
|
+
|
|
171
|
+
self.class_priors_ = np.array([p0, p1])
|
|
172
|
+
self.within_variance_ = within
|
|
173
|
+
self.between_variance_ = between
|
|
174
|
+
self.cvr_scores_ = between / (between + within + self.epsilon)
|
|
175
|
+
self.selected_indices_ = np.argsort(
|
|
176
|
+
-self.cvr_scores_, kind="stable"
|
|
177
|
+
)[: self.n_features]
|
|
178
|
+
selected_scores = self.cvr_scores_[self.selected_indices_]
|
|
179
|
+
self.weights_ = selected_scores / (selected_scores.sum() + self.epsilon)
|
|
180
|
+
|
|
181
|
+
retained_raw = self.variance_filter_.get_support(indices=True)
|
|
182
|
+
self.selected_input_indices_ = retained_raw[self.selected_indices_]
|
|
183
|
+
if hasattr(self, "feature_names_in_"):
|
|
184
|
+
self.selected_feature_names_ = self.feature_names_in_[
|
|
185
|
+
self.selected_input_indices_
|
|
186
|
+
]
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
def transform(self, X):
|
|
190
|
+
"""Apply the *frozen* train-fitted projection to new examples."""
|
|
191
|
+
check_is_fitted(self, ["imputer_", "variance_filter_", "scaler_", "weights_"])
|
|
192
|
+
A = self._validate_input(X, reset=False)
|
|
193
|
+
A = self.imputer_.transform(A)
|
|
194
|
+
A = self.variance_filter_.transform(A)
|
|
195
|
+
A = self.scaler_.transform(A)
|
|
196
|
+
z = A[:, self.selected_indices_] @ self.weights_
|
|
197
|
+
return z.reshape(-1, 1)
|
|
198
|
+
|
|
199
|
+
def get_feature_names_out(self, input_features=None):
|
|
200
|
+
"""Return the one-dimensional output feature's name."""
|
|
201
|
+
check_is_fitted(self, "weights_")
|
|
202
|
+
if input_features is not None:
|
|
203
|
+
provided = list(input_features)
|
|
204
|
+
if len(provided) != self.n_features_in_:
|
|
205
|
+
raise ValueError("Incorrect number of input feature names.")
|
|
206
|
+
if hasattr(self, "feature_names_in_") and not np.array_equal(
|
|
207
|
+
self.feature_names_in_, provided
|
|
208
|
+
):
|
|
209
|
+
raise ValueError("input_features differ from fitted feature names.")
|
|
210
|
+
return np.asarray(["vgsp_0"], dtype=object)
|
|
211
|
+
|
|
212
|
+
def __sklearn_tags__(self):
|
|
213
|
+
"""Advertise required labels and support for missing input values."""
|
|
214
|
+
tags = super().__sklearn_tags__()
|
|
215
|
+
tags.target_tags.required = True
|
|
216
|
+
tags.input_tags.allow_nan = True
|
|
217
|
+
return tags
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vgsp-ml
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Supervised variance-guided scalar projection using bounded class-variance ratios
|
|
5
|
+
Author: Mohd Adil Mokti
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/nqmn/vgsp
|
|
8
|
+
Project-URL: Source, https://github.com/nqmn/vgsp
|
|
9
|
+
Project-URL: Issues, https://github.com/nqmn/vgsp/issues
|
|
10
|
+
Project-URL: Research-archive, https://doi.org/10.5281/zenodo.24183611
|
|
11
|
+
Keywords: VGSP,CVR,supervised dimensionality reduction,SDN,DDoS,machine learning
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: numpy>=1.24
|
|
20
|
+
Requires-Dist: scikit-learn<2,>=1.6
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
23
|
+
Requires-Dist: pandas>=2; extra == "dev"
|
|
24
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
25
|
+
Requires-Dist: twine>=6; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# VGSP — Variance-Guided Scalar Projection
|
|
29
|
+
|
|
30
|
+
A `scikit-learn`-compatible **supervised** transformer that maps numeric feature vectors onto one scalar axis using **bounded class-variance ratio (CVR)** weights.
|
|
31
|
+
|
|
32
|
+
This implementation follows `vgspv4.ipynb` (Cell 4) and its training-only imputation, variance filtering and min–max scaling. It is **not** a pretrained DDoS detector and it does not fetch any network data.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
**Before PyPI publication**, clone `https://github.com/nqmn/vgsp` and install:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
python -m pip install -e ".[dev]"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
**After successful PyPI publication:**
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
python -m pip install vgsp-ml
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The distribution name is `vgsp-ml`; the Python import name is `vgsp`.
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from vgsp import VGSP
|
|
54
|
+
from sklearn.model_selection import train_test_split
|
|
55
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
56
|
+
from sklearn.pipeline import Pipeline
|
|
57
|
+
|
|
58
|
+
# X: numeric features only; y: labels for two classes
|
|
59
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
60
|
+
X, y, test_size=0.20, stratify=y, random_state=42
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
model = Pipeline([
|
|
64
|
+
("vgsp", VGSP(n_features=7)),
|
|
65
|
+
("classifier", DecisionTreeClassifier(random_state=42)),
|
|
66
|
+
])
|
|
67
|
+
model.fit(X_train, y_train)
|
|
68
|
+
print(model.score(X_test, y_test))
|
|
69
|
+
print(model.named_steps["vgsp"].selected_input_indices_)
|
|
70
|
+
print(model.named_steps["vgsp"].weights_)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Or use it directly like a `scikit-learn` transformer:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
vgsp = VGSP(n_features=7)
|
|
77
|
+
Z_train = vgsp.fit_transform(X_train, y_train) # shape: (n_train, 1)
|
|
78
|
+
Z_test = vgsp.transform(X_test) # shape: (n_test, 1)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
VGSP **requires labels in `fit`**; unlike PCA it is supervised. `transform` does not accept labels and never refits.
|
|
82
|
+
|
|
83
|
+
## Mathematical definition (binary labels)
|
|
84
|
+
|
|
85
|
+
For feature `j`, with class prior probabilities `p0` and `p1`, class-wise means `mu0,j` and `mu1,j`, and population variances `v0,j` and `v1,j`:
|
|
86
|
+
|
|
87
|
+
- `W_j = p0*v0,j + p1*v1,j`
|
|
88
|
+
- `B_j = p0*p1*(mu0,j-mu1,j)^2`
|
|
89
|
+
- `CVR_j = B_j/(B_j+W_j+epsilon)`
|
|
90
|
+
- `S_k = indices of the largest k CVR values (stable ties)`
|
|
91
|
+
- `w_j = CVR_j/(sum_{i in S_k} CVR_i+epsilon)`
|
|
92
|
+
- `z = X_scaled[:, S_k] @ w`
|
|
93
|
+
|
|
94
|
+
`epsilon` defaults to `1e-10`, and variance is the population variance (`ddof=0`).
|
|
95
|
+
|
|
96
|
+
The bounded CVR criterion is related monotonically to the Fisher score, rather than a claim of an entirely new mathematical separability measure. The research contribution is the CVR-weighted scalar projection mechanism.
|
|
97
|
+
|
|
98
|
+
## What is included inside the transformer
|
|
99
|
+
|
|
100
|
+
Each `VGSP.fit(X_train, y_train)` performs the following operations using **training data only**:
|
|
101
|
+
|
|
102
|
+
1. Converts positive/negative infinity to missing values and applies **median imputation** (`SimpleImputer(keep_empty_features=True)`).
|
|
103
|
+
2. Removes constant columns (`VarianceThreshold(0.0)`).
|
|
104
|
+
3. Learns the **MinMaxScaler**.
|
|
105
|
+
4. Computes **CVR**, ranks features, and freezes `k` indices and weights.
|
|
106
|
+
|
|
107
|
+
`VGSP.transform(X_valid_or_test)` applies the same fitted imputer, variance filter, scaler and projection weights without recomputing CVR. With a scikit-learn `Pipeline`, these stages are refitted only to each CV training fold.
|
|
108
|
+
|
|
109
|
+
## Evaluation protocol preserved from notebook v4
|
|
110
|
+
|
|
111
|
+
The research notebook uses a **stratified 80:20 split** and **five-fold `StratifiedKFold` on the 80% development portion**. The choice `n_features=7` reflects the latest InSDN development selection. This library **does not automatically tune k**; tuning and final evaluation stay outside the transformer and must never involve the 20% test set.
|
|
112
|
+
|
|
113
|
+
For the additional DDOSDN2025 evaluation that fixes the **same seven feature names from InSDN**, explicitly pass `X[FIXED_FEATURE_NAMES]` for that comparison. By default, `VGSP` ranks features locally within the data passed to `fit`; it does **not** claim that selected feature identities transfer between datasets automatically.
|
|
114
|
+
|
|
115
|
+
## Scope and limitations
|
|
116
|
+
|
|
117
|
+
- Binary supervised projection only, for numeric tabular features.
|
|
118
|
+
- `Protocol` coded numerically is a methodological assumption in the supplied research; this package does not imply ordinal meaning is generally appropriate.
|
|
119
|
+
- A scalar representation is not invertible; no `inverse_transform` is defined.
|
|
120
|
+
- A single scalar downstream input does not mean upstream data capture or flow feature-extraction cost disappears.
|
|
121
|
+
- The dataset is not bundled into the package; no DDoS training/evaluation results are guaranteed on other data.
|
|
122
|
+
|
|
123
|
+
## Development and testing
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
python -m pip install -e ".[dev]"
|
|
127
|
+
python -m pytest -q
|
|
128
|
+
python examples/basic_usage.py
|
|
129
|
+
python -m build
|
|
130
|
+
python -m twine check dist/*
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Publication checklist
|
|
134
|
+
|
|
135
|
+
1. Confirm the distribution name `vgsp-ml` is available on PyPI (or choose another) and ensure it is not confused with `PyGSP`, which is an existing *graph signal processing* package.
|
|
136
|
+
2. Preserve the existing Apache-2.0 `LICENSE` already in the repository.
|
|
137
|
+
3. Confirm the source code and PyPI metadata refer to `https://github.com/nqmn/vgsp`.
|
|
138
|
+
4. Run tests and build the distributions.
|
|
139
|
+
5. Trial-publish to TestPyPI, then publish to PyPI using a verified project and preferably GitHub Actions Trusted Publishing.
|
|
140
|
+
6. An earlier research notebook snapshot already has a Zenodo DOI: https://doi.org/10.5281/zenodo.24183611. If citing this newly packaged release, archive its exact source version separately and verify the new version DOI. PyPI alone does not assign DOIs.
|
|
141
|
+
|
|
142
|
+
The manuscript and notebook are research references; confirm the final manuscript and published implementation are aligned before public release.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
PYPI_README.md
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/vgsp/__init__.py
|
|
6
|
+
src/vgsp/_vgsp.py
|
|
7
|
+
src/vgsp_ml.egg-info/PKG-INFO
|
|
8
|
+
src/vgsp_ml.egg-info/SOURCES.txt
|
|
9
|
+
src/vgsp_ml.egg-info/dependency_links.txt
|
|
10
|
+
src/vgsp_ml.egg-info/requires.txt
|
|
11
|
+
src/vgsp_ml.egg-info/top_level.txt
|
|
12
|
+
tests/test_vgsp.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
vgsp
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import pytest
|
|
4
|
+
from numpy.testing import assert_allclose, assert_array_equal
|
|
5
|
+
from sklearn.model_selection import StratifiedKFold, cross_val_score
|
|
6
|
+
from sklearn.pipeline import Pipeline
|
|
7
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
8
|
+
|
|
9
|
+
from vgsp import VGSP
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def data():
|
|
13
|
+
# Deliberately different scales, a missing value, and a constant feature.
|
|
14
|
+
X = pd.DataFrame({
|
|
15
|
+
"flow": [0., 1., 2., 3., 8., 9., 10., 11.],
|
|
16
|
+
"packets": [3., np.nan, 5., 7., 2., 4., 5., 9.],
|
|
17
|
+
"constant": [5.] * 8,
|
|
18
|
+
"rate": [0., 1., 0., 1., 2., 2., 3., 3.],
|
|
19
|
+
})
|
|
20
|
+
y = np.array([0, 0, 0, 0, 1, 1, 1, 1])
|
|
21
|
+
return X, y
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_scalar_output_and_normalized_score():
|
|
25
|
+
X, y = data()
|
|
26
|
+
m = VGSP(n_features=2).fit(X, y)
|
|
27
|
+
Z = m.transform(X)
|
|
28
|
+
assert Z.shape == (8, 1)
|
|
29
|
+
assert np.all((0 <= m.cvr_scores_) & (m.cvr_scores_ < 1))
|
|
30
|
+
assert m.weights_.sum() <= 1
|
|
31
|
+
assert_array_equal(m.get_feature_names_out(), ["vgsp_0"])
|
|
32
|
+
assert len(m.selected_input_indices_) == 2
|
|
33
|
+
assert "constant" not in m.selected_feature_names_
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_formula_and_projection_match_notebook_cell_4():
|
|
37
|
+
X, y = data()
|
|
38
|
+
m = VGSP(n_features=2).fit(X, y)
|
|
39
|
+
# Independent notebook-equivalent formula on the fitted preprocessing output.
|
|
40
|
+
A = m.scaler_.transform(m.variance_filter_.transform(
|
|
41
|
+
m.imputer_.transform(X.to_numpy())
|
|
42
|
+
))
|
|
43
|
+
A0, A1 = A[y == 0], A[y == 1]
|
|
44
|
+
p0, p1 = len(A0) / len(A), len(A1) / len(A)
|
|
45
|
+
W = p0 * A0.var(axis=0) + p1 * A1.var(axis=0)
|
|
46
|
+
B = p0 * p1 * (A0.mean(axis=0) - A1.mean(axis=0)) ** 2
|
|
47
|
+
cvr = B / (B + W + 1e-10)
|
|
48
|
+
idx = np.argsort(-cvr, kind="stable")[:2]
|
|
49
|
+
weights = cvr[idx] / (cvr[idx].sum() + 1e-10)
|
|
50
|
+
assert_allclose(m.cvr_scores_, cvr, rtol=0, atol=1e-15)
|
|
51
|
+
assert_array_equal(m.selected_indices_, idx)
|
|
52
|
+
assert_allclose(m.weights_, weights, rtol=0, atol=1e-15)
|
|
53
|
+
assert_allclose(m.transform(X).ravel(), A[:, idx] @ weights, atol=1e-15)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_no_refit_during_transform():
|
|
57
|
+
X, y = data()
|
|
58
|
+
m = VGSP(n_features=2).fit(X, y)
|
|
59
|
+
old_weights = m.weights_.copy()
|
|
60
|
+
old_scores = m.cvr_scores_.copy()
|
|
61
|
+
extreme = X.iloc[:2].copy()
|
|
62
|
+
extreme.loc[:, "flow"] = 1e8
|
|
63
|
+
m.transform(extreme)
|
|
64
|
+
assert_array_equal(m.weights_, old_weights)
|
|
65
|
+
assert_array_equal(m.cvr_scores_, old_scores)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_column_order_is_frozen():
|
|
69
|
+
X, y = data()
|
|
70
|
+
m = VGSP(n_features=2).fit(X, y)
|
|
71
|
+
with pytest.raises(ValueError, match="columns do not match"):
|
|
72
|
+
m.transform(X[list(reversed(X.columns))])
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_fit_requires_binary_labels():
|
|
76
|
+
X, y = data()
|
|
77
|
+
with pytest.raises(ValueError, match="exactly two classes"):
|
|
78
|
+
VGSP(n_features=2).fit(X, np.zeros_like(y))
|
|
79
|
+
with pytest.raises(ValueError, match="requires binary labels"):
|
|
80
|
+
VGSP(n_features=2).fit(X, None)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_too_many_features_rejected():
|
|
84
|
+
X, y = data()
|
|
85
|
+
with pytest.raises(ValueError, match="exceeds"):
|
|
86
|
+
VGSP(n_features=4).fit(X, y)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_pipeline_cross_validation_and_dataframe_output():
|
|
90
|
+
rng = np.random.default_rng(7)
|
|
91
|
+
X = rng.normal(size=(150, 9))
|
|
92
|
+
y = np.repeat([0, 1], 75)
|
|
93
|
+
X[y == 1, 0] += 2.0
|
|
94
|
+
model = Pipeline([
|
|
95
|
+
("vgsp", VGSP(n_features=7)),
|
|
96
|
+
("dt", DecisionTreeClassifier(random_state=42)),
|
|
97
|
+
])
|
|
98
|
+
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
|
|
99
|
+
scores = cross_val_score(model, X, y, cv=cv, scoring="f1_macro")
|
|
100
|
+
assert scores.shape == (5,)
|
|
101
|
+
assert np.isfinite(scores).all()
|
|
102
|
+
out = VGSP(n_features=7).set_output(transform="pandas").fit_transform(X, y)
|
|
103
|
+
assert list(out.columns) == ["vgsp_0"]
|
|
104
|
+
assert out.shape == (150, 1)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_infinity_is_imputed_using_training_data():
|
|
108
|
+
X, y = data()
|
|
109
|
+
m = VGSP(n_features=2).fit(X, y)
|
|
110
|
+
invalid = X.iloc[:2].copy()
|
|
111
|
+
invalid.loc[:, "flow"] = np.inf
|
|
112
|
+
assert np.isfinite(m.transform(invalid)).all()
|