fnsga-selector 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.
- fnsga_selector-0.1.0/LICENSE +21 -0
- fnsga_selector-0.1.0/MANIFEST.in +3 -0
- fnsga_selector-0.1.0/PKG-INFO +157 -0
- fnsga_selector-0.1.0/README.md +131 -0
- fnsga_selector-0.1.0/RELEASING.md +42 -0
- fnsga_selector-0.1.0/pyproject.toml +46 -0
- fnsga_selector-0.1.0/recipe/recipe.yaml +48 -0
- fnsga_selector-0.1.0/setup.cfg +4 -0
- fnsga_selector-0.1.0/src/FNSGA.py +5 -0
- fnsga_selector-0.1.0/src/fnsga_selector/__init__.py +5 -0
- fnsga_selector-0.1.0/src/fnsga_selector/_evaluation.py +98 -0
- fnsga_selector-0.1.0/src/fnsga_selector/_params.py +54 -0
- fnsga_selector-0.1.0/src/fnsga_selector/_pareto.py +63 -0
- fnsga_selector-0.1.0/src/fnsga_selector/_plotting.py +101 -0
- fnsga_selector-0.1.0/src/fnsga_selector/_search.py +149 -0
- fnsga_selector-0.1.0/src/fnsga_selector/examples/__init__.py +1 -0
- fnsga_selector-0.1.0/src/fnsga_selector/examples/numpy_ridge_rmse.py +45 -0
- fnsga_selector-0.1.0/src/fnsga_selector/examples/scipy_balanced_accuracy.py +48 -0
- fnsga_selector-0.1.0/src/fnsga_selector/examples/sklearn_roc_auc.py +35 -0
- fnsga_selector-0.1.0/src/fnsga_selector/examples/statsmodels_poisson_deviance.py +42 -0
- fnsga_selector-0.1.0/src/fnsga_selector/presets/__init__.py +1 -0
- fnsga_selector-0.1.0/src/fnsga_selector/presets/tuned_parameters.csv +5 -0
- fnsga_selector-0.1.0/src/fnsga_selector/selector.py +238 -0
- fnsga_selector-0.1.0/src/fnsga_selector.egg-info/PKG-INFO +157 -0
- fnsga_selector-0.1.0/src/fnsga_selector.egg-info/SOURCES.txt +31 -0
- fnsga_selector-0.1.0/src/fnsga_selector.egg-info/dependency_links.txt +1 -0
- fnsga_selector-0.1.0/src/fnsga_selector.egg-info/requires.txt +11 -0
- fnsga_selector-0.1.0/src/fnsga_selector.egg-info/top_level.txt +2 -0
- fnsga_selector-0.1.0/tests/test_custom_models.py +93 -0
- fnsga_selector-0.1.0/tests/test_plotting.py +63 -0
- fnsga_selector-0.1.0/tests/test_results.py +73 -0
- fnsga_selector-0.1.0/tests/test_selector.py +150 -0
- fnsga_selector-0.1.0/tests/test_sense.py +93 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The feature-selection contributors
|
|
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,157 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fnsga-selector
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pareto feature selection with improved FNSGA for custom and scikit-learn models
|
|
5
|
+
Author: Erin Fortin and contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Research source, https://github.com/ekfortin9059/feature-selection
|
|
8
|
+
Keywords: feature selection,multiobjective optimization,FNSGA,scikit-learn
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Requires-Python: >=3.11
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: numpy>=1.24
|
|
17
|
+
Requires-Dist: scikit-learn>=1.6
|
|
18
|
+
Requires-Dist: matplotlib>=3.7
|
|
19
|
+
Requires-Dist: pandas>=2.0
|
|
20
|
+
Provides-Extra: examples
|
|
21
|
+
Requires-Dist: scipy>=1.10; extra == "examples"
|
|
22
|
+
Requires-Dist: statsmodels>=0.14; extra == "examples"
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# FNSGA Selector
|
|
28
|
+
|
|
29
|
+
Find subsets of predictors that trade validation score against feature count. `FNSGA` runs the improved FNSGA on dense numeric features and a single classification or regression target. Supply a scikit-learn estimator or a training function for a model from any library.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
Requires Python 3.11 or later. After publication, install with `python -m pip install fnsga-selector`. For a local checkout, run `python -m pip install .` in the directory containing `pyproject.toml`. For a conda release, run `conda install --override-channels -c YOUR_CHANNEL -c conda-forge fnsga-selector`, substituting the publisher's Anaconda.org channel.
|
|
34
|
+
|
|
35
|
+
## Using a scikit-learn estimator
|
|
36
|
+
|
|
37
|
+
This example reserves an independent test set before selecting features. The search scores candidate masks on a validation split within the training data. The pipeline then fits its final regressor on all the training rows using the chosen columns.
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from sklearn.datasets import load_diabetes
|
|
41
|
+
from sklearn.linear_model import LinearRegression
|
|
42
|
+
from sklearn.model_selection import train_test_split
|
|
43
|
+
from sklearn.pipeline import make_pipeline
|
|
44
|
+
|
|
45
|
+
from FNSGA import FNSGA
|
|
46
|
+
|
|
47
|
+
X, y = load_diabetes(return_X_y=True)
|
|
48
|
+
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
|
|
49
|
+
|
|
50
|
+
select = FNSGA(
|
|
51
|
+
LinearRegression(), population_size=24, generations=5, random_state=7
|
|
52
|
+
)
|
|
53
|
+
model = make_pipeline(select, LinearRegression()).fit(X_train, y_train)
|
|
54
|
+
|
|
55
|
+
for subset in select.pareto_front_:
|
|
56
|
+
print(subset.indices, subset.score)
|
|
57
|
+
print("Selected columns", select.get_support(indices=True))
|
|
58
|
+
print("Test R²", model.score(X_test, y_test))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The same class is available as `from fnsga_selector import FNSGA`.
|
|
62
|
+
|
|
63
|
+
## Fitness and result export
|
|
64
|
+
|
|
65
|
+
By default, `fit(X, y)` reserves 20% of the rows for validation once per search. Every candidate uses the same split. For each distinct feature mask the selector clones the supplied estimator (including pipeline steps and hyperparameters), fits it on the training rows with those columns, and scores it on the validation rows with the same columns. A custom `fit_model` callback creates the trained model instead. When enabled, model-based seeding uses a separate fit on the training rows with all columns.
|
|
66
|
+
|
|
67
|
+
Choose `sense` for the value your scorer actually returns. The Pareto sort always minimizes both objectives.
|
|
68
|
+
|
|
69
|
+
| Scorer output for four features | Sense | Fitness passed to the sort |
|
|
70
|
+
| --- | --- | --- |
|
|
71
|
+
| R² of 0.72 | `"max"` (default) | `(-0.72, 4)` |
|
|
72
|
+
| Raw MAE of 2.5 | `"min"` | `(2.5, 4)` |
|
|
73
|
+
| scikit-learn's `"neg_mean_absolute_error"` returns −2.5 | `"max"` | `(2.5, 4)` |
|
|
74
|
+
|
|
75
|
+
The long forms `"maximize"`, `"maximise"`, `"minimize"`, and `"minimise"` are also accepted. Plots and `FeatureSubset.score` show the original validation metric. Repeated masks reuse their cached score. In the example above, `model.score(X_test, y_test)` evaluates the final pipeline on an independent test set after feature selection.
|
|
76
|
+
|
|
77
|
+
Export the final Pareto set to a pandas DataFrame. Supplying a path also writes a CSV using the stored scores. Row numbers match the membership plot, and `selected` marks the subset used by `transform()`.
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
results = select.to_dataframe("pareto-diabetes.csv", feature_names=load_diabetes().feature_names)
|
|
81
|
+
print(results[["subset_id", "sense", "validation_score", "score_objective", "n_features", "selected"]])
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Use `select.to_dataframe()` for an in-memory table. The two fitness columns are `score_objective` and `n_features`. The existing `neg_validation_score` column retains its meaning of minus the raw validation score for either sense. Feature indices are zero-based. String column names from a training DataFrame are used automatically. The CSV stores feature indices and names as JSON arrays, which can be read back with `json.loads`.
|
|
85
|
+
|
|
86
|
+
## Plotting the Pareto set
|
|
87
|
+
|
|
88
|
+
Use the fitted `select` from the example above. The front shows validation score against feature count. A ring marks the subset used by `transform`. Subsets with identical coordinates share a count label. The membership plot shows each distinct subset in its own row, including ties. Colored cells identify the included features.
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
import matplotlib.pyplot as plt
|
|
92
|
+
|
|
93
|
+
fig, (front, subsets) = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
|
|
94
|
+
select.plot_pareto_front(ax=front, score_label="Validation R²")
|
|
95
|
+
select.plot_pareto_set(ax=subsets, feature_names=load_diabetes().feature_names)
|
|
96
|
+
fig.savefig("pareto-diabetes.png", dpi=180)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Both methods return a Matplotlib Axes. Omit `ax` to create a figure, or call `plt.show()` to display it. The membership plot uses column names recorded during fitting when available and otherwise labels features by zero-based index.
|
|
100
|
+
|
|
101
|
+
## Using a custom model
|
|
102
|
+
|
|
103
|
+
Pass `fit_model` and set `task` to `"regression"` or `"classification"`. The training function receives a NumPy matrix containing the candidate columns and a one-dimensional training target. Each call should create and return a freshly trained model. If model-based seeding is active, the search also calls the function with all columns.
|
|
104
|
+
|
|
105
|
+
When the returned object has `predict(X)`, the default validation score is R² for regression or accuracy for classification. For another interface or metric, pass `scoring(model, X_valid, y_valid)`. It receives the same selected columns on held-out rows and returns one finite number in the chosen sense.
|
|
106
|
+
|
|
107
|
+
This example fits a linear model directly with NumPy and minimizes its mean absolute error. The training function returns coefficients and an intercept.
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
import numpy as np
|
|
111
|
+
|
|
112
|
+
from fnsga_selector import FNSGA
|
|
113
|
+
|
|
114
|
+
def fit_linear(X, y):
|
|
115
|
+
weights = np.linalg.lstsq(X - X.mean(axis=0), y - y.mean(), rcond=None)[0]
|
|
116
|
+
return weights, y.mean() - X.mean(axis=0) @ weights
|
|
117
|
+
|
|
118
|
+
def mae(model, X, y):
|
|
119
|
+
weights, intercept = model
|
|
120
|
+
return np.mean(np.abs(y - (X @ weights + intercept)))
|
|
121
|
+
|
|
122
|
+
rng = np.random.default_rng(7)
|
|
123
|
+
X = rng.normal(size=(120, 8))
|
|
124
|
+
y = 3 * X[:, 2] - X[:, 5] + rng.normal(scale=0.2, size=len(X))
|
|
125
|
+
selector = FNSGA(
|
|
126
|
+
fit_model=fit_linear, task="regression", scoring=mae, sense="min", random_state=7
|
|
127
|
+
)
|
|
128
|
+
selector.fit(X[:100], y[:100])
|
|
129
|
+
model = fit_linear(selector.transform(X[:100]), y[:100])
|
|
130
|
+
print("Selected columns", selector.get_support(indices=True))
|
|
131
|
+
print("Test MAE", mae(model, selector.transform(X[100:]), y[100:]))
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Runnable examples
|
|
135
|
+
|
|
136
|
+
From a checkout, `python -m pip install ".[examples]"` installs the package and the example dependencies. With an existing installation, install `statsmodels` to run the Poisson example. Each module runs on bundled or generated data and evaluates the selected model once on a separate test set.
|
|
137
|
+
|
|
138
|
+
| Command | Model | Selection metric |
|
|
139
|
+
| --- | --- | --- |
|
|
140
|
+
| `python -m fnsga_selector.examples.sklearn_roc_auc` | scikit-learn logistic regression | Maximize ROC AUC |
|
|
141
|
+
| `python -m fnsga_selector.examples.numpy_ridge_rmse` | NumPy ridge regression | Minimize RMSE |
|
|
142
|
+
| `python -m fnsga_selector.examples.scipy_balanced_accuracy` | SciPy nearest neighbor | Maximize balanced accuracy |
|
|
143
|
+
| `python -m fnsga_selector.examples.statsmodels_poisson_deviance` | statsmodels Poisson GLM | Minimize mean Poisson deviance |
|
|
144
|
+
|
|
145
|
+
## Search settings and results
|
|
146
|
+
|
|
147
|
+
- FNSGA uses model-based seeding, binary tournaments, crossover, mutation, and add/remove/merge local searches. For seeding, the selector uses numeric `feature_importances_` or `coef_` values when available. Otherwise features have equal initial weights.
|
|
148
|
+
- For a scikit-learn estimator, `scoring` accepts a scorer name or a callable `(model, X, y)`. The default uses the estimator's score. Classification uses a stratified validation split with either model interface.
|
|
149
|
+
- The default search uses 100 individuals and 20 generations. The `preset` argument selects tuned search parameters for `LinReg`, `LogReg`, `SVC` or `DT`. The defaults are `LinReg` for regression and `LogReg` for classification, including custom models. Override individual values with `search_options`, for example `{"mutation_prob": 0.08}`. FNSGA accepts `crossover_prob`, `mutation_prob`, `seeding_prop`, `ones_prop`, `ls_start`, and `ls_end`.
|
|
150
|
+
- `pareto_front_` lists subsets by increasing size. Each `FeatureSubset` contains zero-based column indices and its validation score. `transform` and `get_support` use the solution with the best validation metric in the chosen sense, breaking ties by smaller size and then column indices. To use another trade-off, slice the original columns using that solution's indices.
|
|
151
|
+
- The selector caches each subset's validation score for the duration of a fit. A fixed integer `random_state` reproduces the split and search. Set the model's own random seed when training is stochastic. Report performance on held-out data or run the entire pipeline within outer cross-validation. The default split assumes independent rows.
|
|
152
|
+
|
|
153
|
+
## Research provenance
|
|
154
|
+
|
|
155
|
+
This package adapts Erin Fortin's feature-selection research code and ships its tuned parameter tables. Each search considers only nonempty masks. When all possible nonempty subsets fit in the population budget, the selector evaluates the entire space. On wider datasets FNSGA bounds duplicate-generation attempts and fills any remaining slots with unseen masks. It allows mutation of every column and shifts negative feature weights before computing local-search probabilities. These changes affect seeded trajectories and comparisons with archived runs. The original experiment scripts, plots, and dataset loaders are available in the research repository. [Research source](https://github.com/ekfortin9059/feature-selection/tree/96b79688d3f4084adc94687f78a12a96d8ce92fb)
|
|
156
|
+
|
|
157
|
+
Distributed under the MIT license.
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# FNSGA Selector
|
|
2
|
+
|
|
3
|
+
Find subsets of predictors that trade validation score against feature count. `FNSGA` runs the improved FNSGA on dense numeric features and a single classification or regression target. Supply a scikit-learn estimator or a training function for a model from any library.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
Requires Python 3.11 or later. After publication, install with `python -m pip install fnsga-selector`. For a local checkout, run `python -m pip install .` in the directory containing `pyproject.toml`. For a conda release, run `conda install --override-channels -c YOUR_CHANNEL -c conda-forge fnsga-selector`, substituting the publisher's Anaconda.org channel.
|
|
8
|
+
|
|
9
|
+
## Using a scikit-learn estimator
|
|
10
|
+
|
|
11
|
+
This example reserves an independent test set before selecting features. The search scores candidate masks on a validation split within the training data. The pipeline then fits its final regressor on all the training rows using the chosen columns.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from sklearn.datasets import load_diabetes
|
|
15
|
+
from sklearn.linear_model import LinearRegression
|
|
16
|
+
from sklearn.model_selection import train_test_split
|
|
17
|
+
from sklearn.pipeline import make_pipeline
|
|
18
|
+
|
|
19
|
+
from FNSGA import FNSGA
|
|
20
|
+
|
|
21
|
+
X, y = load_diabetes(return_X_y=True)
|
|
22
|
+
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
|
|
23
|
+
|
|
24
|
+
select = FNSGA(
|
|
25
|
+
LinearRegression(), population_size=24, generations=5, random_state=7
|
|
26
|
+
)
|
|
27
|
+
model = make_pipeline(select, LinearRegression()).fit(X_train, y_train)
|
|
28
|
+
|
|
29
|
+
for subset in select.pareto_front_:
|
|
30
|
+
print(subset.indices, subset.score)
|
|
31
|
+
print("Selected columns", select.get_support(indices=True))
|
|
32
|
+
print("Test R²", model.score(X_test, y_test))
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The same class is available as `from fnsga_selector import FNSGA`.
|
|
36
|
+
|
|
37
|
+
## Fitness and result export
|
|
38
|
+
|
|
39
|
+
By default, `fit(X, y)` reserves 20% of the rows for validation once per search. Every candidate uses the same split. For each distinct feature mask the selector clones the supplied estimator (including pipeline steps and hyperparameters), fits it on the training rows with those columns, and scores it on the validation rows with the same columns. A custom `fit_model` callback creates the trained model instead. When enabled, model-based seeding uses a separate fit on the training rows with all columns.
|
|
40
|
+
|
|
41
|
+
Choose `sense` for the value your scorer actually returns. The Pareto sort always minimizes both objectives.
|
|
42
|
+
|
|
43
|
+
| Scorer output for four features | Sense | Fitness passed to the sort |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| R² of 0.72 | `"max"` (default) | `(-0.72, 4)` |
|
|
46
|
+
| Raw MAE of 2.5 | `"min"` | `(2.5, 4)` |
|
|
47
|
+
| scikit-learn's `"neg_mean_absolute_error"` returns −2.5 | `"max"` | `(2.5, 4)` |
|
|
48
|
+
|
|
49
|
+
The long forms `"maximize"`, `"maximise"`, `"minimize"`, and `"minimise"` are also accepted. Plots and `FeatureSubset.score` show the original validation metric. Repeated masks reuse their cached score. In the example above, `model.score(X_test, y_test)` evaluates the final pipeline on an independent test set after feature selection.
|
|
50
|
+
|
|
51
|
+
Export the final Pareto set to a pandas DataFrame. Supplying a path also writes a CSV using the stored scores. Row numbers match the membership plot, and `selected` marks the subset used by `transform()`.
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
results = select.to_dataframe("pareto-diabetes.csv", feature_names=load_diabetes().feature_names)
|
|
55
|
+
print(results[["subset_id", "sense", "validation_score", "score_objective", "n_features", "selected"]])
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Use `select.to_dataframe()` for an in-memory table. The two fitness columns are `score_objective` and `n_features`. The existing `neg_validation_score` column retains its meaning of minus the raw validation score for either sense. Feature indices are zero-based. String column names from a training DataFrame are used automatically. The CSV stores feature indices and names as JSON arrays, which can be read back with `json.loads`.
|
|
59
|
+
|
|
60
|
+
## Plotting the Pareto set
|
|
61
|
+
|
|
62
|
+
Use the fitted `select` from the example above. The front shows validation score against feature count. A ring marks the subset used by `transform`. Subsets with identical coordinates share a count label. The membership plot shows each distinct subset in its own row, including ties. Colored cells identify the included features.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import matplotlib.pyplot as plt
|
|
66
|
+
|
|
67
|
+
fig, (front, subsets) = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
|
|
68
|
+
select.plot_pareto_front(ax=front, score_label="Validation R²")
|
|
69
|
+
select.plot_pareto_set(ax=subsets, feature_names=load_diabetes().feature_names)
|
|
70
|
+
fig.savefig("pareto-diabetes.png", dpi=180)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Both methods return a Matplotlib Axes. Omit `ax` to create a figure, or call `plt.show()` to display it. The membership plot uses column names recorded during fitting when available and otherwise labels features by zero-based index.
|
|
74
|
+
|
|
75
|
+
## Using a custom model
|
|
76
|
+
|
|
77
|
+
Pass `fit_model` and set `task` to `"regression"` or `"classification"`. The training function receives a NumPy matrix containing the candidate columns and a one-dimensional training target. Each call should create and return a freshly trained model. If model-based seeding is active, the search also calls the function with all columns.
|
|
78
|
+
|
|
79
|
+
When the returned object has `predict(X)`, the default validation score is R² for regression or accuracy for classification. For another interface or metric, pass `scoring(model, X_valid, y_valid)`. It receives the same selected columns on held-out rows and returns one finite number in the chosen sense.
|
|
80
|
+
|
|
81
|
+
This example fits a linear model directly with NumPy and minimizes its mean absolute error. The training function returns coefficients and an intercept.
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
import numpy as np
|
|
85
|
+
|
|
86
|
+
from fnsga_selector import FNSGA
|
|
87
|
+
|
|
88
|
+
def fit_linear(X, y):
|
|
89
|
+
weights = np.linalg.lstsq(X - X.mean(axis=0), y - y.mean(), rcond=None)[0]
|
|
90
|
+
return weights, y.mean() - X.mean(axis=0) @ weights
|
|
91
|
+
|
|
92
|
+
def mae(model, X, y):
|
|
93
|
+
weights, intercept = model
|
|
94
|
+
return np.mean(np.abs(y - (X @ weights + intercept)))
|
|
95
|
+
|
|
96
|
+
rng = np.random.default_rng(7)
|
|
97
|
+
X = rng.normal(size=(120, 8))
|
|
98
|
+
y = 3 * X[:, 2] - X[:, 5] + rng.normal(scale=0.2, size=len(X))
|
|
99
|
+
selector = FNSGA(
|
|
100
|
+
fit_model=fit_linear, task="regression", scoring=mae, sense="min", random_state=7
|
|
101
|
+
)
|
|
102
|
+
selector.fit(X[:100], y[:100])
|
|
103
|
+
model = fit_linear(selector.transform(X[:100]), y[:100])
|
|
104
|
+
print("Selected columns", selector.get_support(indices=True))
|
|
105
|
+
print("Test MAE", mae(model, selector.transform(X[100:]), y[100:]))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Runnable examples
|
|
109
|
+
|
|
110
|
+
From a checkout, `python -m pip install ".[examples]"` installs the package and the example dependencies. With an existing installation, install `statsmodels` to run the Poisson example. Each module runs on bundled or generated data and evaluates the selected model once on a separate test set.
|
|
111
|
+
|
|
112
|
+
| Command | Model | Selection metric |
|
|
113
|
+
| --- | --- | --- |
|
|
114
|
+
| `python -m fnsga_selector.examples.sklearn_roc_auc` | scikit-learn logistic regression | Maximize ROC AUC |
|
|
115
|
+
| `python -m fnsga_selector.examples.numpy_ridge_rmse` | NumPy ridge regression | Minimize RMSE |
|
|
116
|
+
| `python -m fnsga_selector.examples.scipy_balanced_accuracy` | SciPy nearest neighbor | Maximize balanced accuracy |
|
|
117
|
+
| `python -m fnsga_selector.examples.statsmodels_poisson_deviance` | statsmodels Poisson GLM | Minimize mean Poisson deviance |
|
|
118
|
+
|
|
119
|
+
## Search settings and results
|
|
120
|
+
|
|
121
|
+
- FNSGA uses model-based seeding, binary tournaments, crossover, mutation, and add/remove/merge local searches. For seeding, the selector uses numeric `feature_importances_` or `coef_` values when available. Otherwise features have equal initial weights.
|
|
122
|
+
- For a scikit-learn estimator, `scoring` accepts a scorer name or a callable `(model, X, y)`. The default uses the estimator's score. Classification uses a stratified validation split with either model interface.
|
|
123
|
+
- The default search uses 100 individuals and 20 generations. The `preset` argument selects tuned search parameters for `LinReg`, `LogReg`, `SVC` or `DT`. The defaults are `LinReg` for regression and `LogReg` for classification, including custom models. Override individual values with `search_options`, for example `{"mutation_prob": 0.08}`. FNSGA accepts `crossover_prob`, `mutation_prob`, `seeding_prop`, `ones_prop`, `ls_start`, and `ls_end`.
|
|
124
|
+
- `pareto_front_` lists subsets by increasing size. Each `FeatureSubset` contains zero-based column indices and its validation score. `transform` and `get_support` use the solution with the best validation metric in the chosen sense, breaking ties by smaller size and then column indices. To use another trade-off, slice the original columns using that solution's indices.
|
|
125
|
+
- The selector caches each subset's validation score for the duration of a fit. A fixed integer `random_state` reproduces the split and search. Set the model's own random seed when training is stochastic. Report performance on held-out data or run the entire pipeline within outer cross-validation. The default split assumes independent rows.
|
|
126
|
+
|
|
127
|
+
## Research provenance
|
|
128
|
+
|
|
129
|
+
This package adapts Erin Fortin's feature-selection research code and ships its tuned parameter tables. Each search considers only nonempty masks. When all possible nonempty subsets fit in the population budget, the selector evaluates the entire space. On wider datasets FNSGA bounds duplicate-generation attempts and fills any remaining slots with unseen masks. It allows mutation of every column and shifts negative feature weights before computing local-search probabilities. These changes affect seeded trajectories and comparisons with archived runs. The original experiment scripts, plots, and dataset loaders are available in the research repository. [Research source](https://github.com/ekfortin9059/feature-selection/tree/96b79688d3f4084adc94687f78a12a96d8ce92fb)
|
|
130
|
+
|
|
131
|
+
Distributed under the MIT license.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Build and publish a release
|
|
2
|
+
|
|
3
|
+
Run commands from the package directory containing `pyproject.toml`. Use a fresh Python 3.11+ environment. Set the release version in `pyproject.toml` and `recipe/recipe.yaml`. Use a new version for each PyPI release and increment the conda build number for a recipe-only rebuild.
|
|
4
|
+
|
|
5
|
+
## Build and test PyPI distributions
|
|
6
|
+
|
|
7
|
+
The included GitHub Actions workflow runs when this package directory is the root of a GitHub repository. It builds the wheel on Linux, Windows and macOS and tests a conda build on Linux.
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
python -m pip install build twine
|
|
11
|
+
python -m build
|
|
12
|
+
python -m twine check --strict dist/*
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The default build creates a source distribution and builds the wheel from it. In a fresh environment install the wheel and run the tests from the source tree. For version 0.1.0 the commands are
|
|
16
|
+
|
|
17
|
+
```text
|
|
18
|
+
python -m pip install "dist/fnsga_selector-0.1.0-py3-none-any.whl[test]"
|
|
19
|
+
python -m pytest -q tests
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Build and test the conda package
|
|
23
|
+
|
|
24
|
+
Install the conda builder with `conda install -c conda-forge rattler-build`. Set the output directory outside the package source tree. The recipe builds a noarch Python package and runs the core tests in a fresh environment.
|
|
25
|
+
|
|
26
|
+
```text
|
|
27
|
+
rattler-build build --recipe recipe/recipe.yaml -c conda-forge --no-include-recipe --output-dir ../conda-output
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Upload the reviewed files
|
|
31
|
+
|
|
32
|
+
When ready, use a PyPI account authorized for the project and an Anaconda.org account authorized for the target channel. Twine accepts a PyPI API token as its password with username `__token__`. The Anaconda CLI prompts for credentials at login. Use a clean dist directory containing only the intended release.
|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
python -m twine upload dist/*
|
|
36
|
+
anaconda login
|
|
37
|
+
anaconda upload --user YOUR_CHANNEL ../conda-output/noarch/fnsga-selector-0.1.0-pyh4616a5c_0.conda
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Use the exact filename printed by rattler-build for the upload. Install the released package using `python -m pip install fnsga-selector==0.1.0` or `conda install --override-channels -c YOUR_CHANNEL -c conda-forge fnsga-selector=0.1.0`.
|
|
41
|
+
|
|
42
|
+
[PyPI publishing guide](https://packaging.python.org/en/latest/tutorials/packaging-projects/) · [Anaconda.org package uploads](https://www.anaconda.com/docs/tools/anaconda-org/user-guide/packages/uploading-packages)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fnsga-selector"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Pareto feature selection with improved FNSGA for custom and scikit-learn models"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{name = "Erin Fortin and contributors"}]
|
|
14
|
+
keywords = ["feature selection", "multiobjective optimization", "FNSGA", "scikit-learn"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Intended Audience :: Science/Research",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["numpy>=1.24", "scikit-learn>=1.6", "matplotlib>=3.7", "pandas>=2.0"]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
"Research source" = "https://github.com/ekfortin9059/feature-selection"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
examples = ["scipy>=1.10", "statsmodels>=0.14"]
|
|
28
|
+
test = ["pytest>=8"]
|
|
29
|
+
|
|
30
|
+
[tool.setuptools]
|
|
31
|
+
py-modules = ["FNSGA"]
|
|
32
|
+
package-dir = {"" = "src"}
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
36
|
+
namespaces = false
|
|
37
|
+
|
|
38
|
+
[tool.setuptools.package-data]
|
|
39
|
+
fnsga_selector = ["presets/*.csv"]
|
|
40
|
+
|
|
41
|
+
[tool.pytest.ini_options]
|
|
42
|
+
testpaths = ["tests"]
|
|
43
|
+
addopts = "--strict-markers"
|
|
44
|
+
|
|
45
|
+
[tool.ruff]
|
|
46
|
+
line-length = 100
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
context:
|
|
2
|
+
version: "0.1.0"
|
|
3
|
+
|
|
4
|
+
package:
|
|
5
|
+
name: fnsga-selector
|
|
6
|
+
version: ${{ version }}
|
|
7
|
+
|
|
8
|
+
source:
|
|
9
|
+
path: ..
|
|
10
|
+
|
|
11
|
+
build:
|
|
12
|
+
number: 0
|
|
13
|
+
noarch: python
|
|
14
|
+
script:
|
|
15
|
+
- python -m pip wheel . --no-deps --no-build-isolation --wheel-dir wheels
|
|
16
|
+
- python -m pip install --no-deps --no-index --find-links wheels fnsga-selector==${{ version }}
|
|
17
|
+
|
|
18
|
+
requirements:
|
|
19
|
+
host:
|
|
20
|
+
- python 3.11.*
|
|
21
|
+
- pip
|
|
22
|
+
- setuptools >=77
|
|
23
|
+
run:
|
|
24
|
+
- python >=3.11
|
|
25
|
+
- numpy >=1.24
|
|
26
|
+
- pandas >=2.0
|
|
27
|
+
- scikit-learn >=1.6
|
|
28
|
+
- matplotlib-base >=3.7
|
|
29
|
+
|
|
30
|
+
tests:
|
|
31
|
+
- python:
|
|
32
|
+
imports:
|
|
33
|
+
- FNSGA
|
|
34
|
+
- fnsga_selector
|
|
35
|
+
pip_check: true
|
|
36
|
+
- script:
|
|
37
|
+
- python -m pytest -q tests
|
|
38
|
+
requirements:
|
|
39
|
+
run:
|
|
40
|
+
- pytest >=8
|
|
41
|
+
files:
|
|
42
|
+
source:
|
|
43
|
+
- tests/
|
|
44
|
+
|
|
45
|
+
about:
|
|
46
|
+
summary: Pareto feature selection with improved FNSGA for custom and scikit-learn models
|
|
47
|
+
license: MIT
|
|
48
|
+
license_file: LICENSE
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Fit-local scoring on a fixed validation split."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from sklearn.base import clone, is_classifier, is_regressor
|
|
5
|
+
from sklearn.metrics import accuracy_score, check_scoring, r2_score
|
|
6
|
+
from sklearn.pipeline import Pipeline
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def model_callbacks(estimator, fit_model, task, scoring):
|
|
10
|
+
"""Resolve the training and validation functions once for the whole search."""
|
|
11
|
+
if (estimator is None) == (fit_model is None):
|
|
12
|
+
raise ValueError("Supply exactly one of estimator and fit_model.")
|
|
13
|
+
if fit_model is not None:
|
|
14
|
+
if not callable(fit_model):
|
|
15
|
+
raise TypeError("fit_model must be callable as fit_model(X_train, y_train).")
|
|
16
|
+
if task not in ("classification", "regression"):
|
|
17
|
+
raise ValueError("Set task to 'classification' or 'regression' when using fit_model.")
|
|
18
|
+
if scoring is not None:
|
|
19
|
+
if not callable(scoring):
|
|
20
|
+
raise TypeError("With fit_model, scoring must be a callable (model, X, y).")
|
|
21
|
+
return task, fit_model, scoring
|
|
22
|
+
metric = accuracy_score if task == "classification" else r2_score
|
|
23
|
+
|
|
24
|
+
def score_predictions(model, X, y):
|
|
25
|
+
if not callable(getattr(model, "predict", None)):
|
|
26
|
+
raise TypeError("Supply scoring(model, X, y) for a model without predict(X).")
|
|
27
|
+
return metric(y, model.predict(X))
|
|
28
|
+
|
|
29
|
+
return task, fit_model, score_predictions
|
|
30
|
+
|
|
31
|
+
if is_classifier(estimator):
|
|
32
|
+
inferred = "classification"
|
|
33
|
+
elif is_regressor(estimator):
|
|
34
|
+
inferred = "regression"
|
|
35
|
+
else:
|
|
36
|
+
raise ValueError("Use fit_model and task for models outside scikit-learn.")
|
|
37
|
+
if task is not None and task != inferred:
|
|
38
|
+
raise ValueError(f"task must match the estimator's task ({inferred!r}).")
|
|
39
|
+
|
|
40
|
+
def train_clone(X, y):
|
|
41
|
+
return clone(estimator).fit(X, y)
|
|
42
|
+
|
|
43
|
+
return inferred, train_clone, check_scoring(estimator, scoring=scoring)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Evaluator:
|
|
47
|
+
def __init__(self, train, scorer, split, score_sign):
|
|
48
|
+
self.train = train
|
|
49
|
+
self.scorer = scorer
|
|
50
|
+
self.score_sign = score_sign
|
|
51
|
+
self.X_train, self.X_valid, self.y_train, self.y_valid = split
|
|
52
|
+
self.n_features = self.X_train.shape[1]
|
|
53
|
+
self.scores = {}
|
|
54
|
+
|
|
55
|
+
def score(self, mask):
|
|
56
|
+
key = mask.tobytes()
|
|
57
|
+
if key not in self.scores:
|
|
58
|
+
if not mask.any():
|
|
59
|
+
raise ValueError("At least one feature must be selected.")
|
|
60
|
+
model = self.train(self.X_train[:, mask], self.y_train)
|
|
61
|
+
score = self.scorer(model, self.X_valid[:, mask], self.y_valid)
|
|
62
|
+
if np.ndim(score) != 0:
|
|
63
|
+
raise ValueError("The validation scorer must return a single scalar score.")
|
|
64
|
+
score = float(score)
|
|
65
|
+
if not np.isfinite(score):
|
|
66
|
+
raise ValueError("The validation scorer returned a non-finite value.")
|
|
67
|
+
self.scores[key] = score
|
|
68
|
+
return self.scores[key]
|
|
69
|
+
|
|
70
|
+
def objectives(self, masks):
|
|
71
|
+
return np.array([(self.score_sign * self.score(mask), mask.sum()) for mask in masks])
|
|
72
|
+
|
|
73
|
+
def importances(self):
|
|
74
|
+
model = self.train(self.X_train, self.y_train)
|
|
75
|
+
estimator = model[-1] if isinstance(model, Pipeline) else model
|
|
76
|
+
# A pipeline may change the feature count or reorder its inputs.
|
|
77
|
+
if isinstance(model, Pipeline) and len(model) > 1:
|
|
78
|
+
names = [f"x{i}" for i in range(self.n_features)]
|
|
79
|
+
try:
|
|
80
|
+
out = model[:-1].get_feature_names_out(names)
|
|
81
|
+
except (AttributeError, NotImplementedError):
|
|
82
|
+
return np.ones(self.n_features)
|
|
83
|
+
if not np.array_equal(names, out):
|
|
84
|
+
return np.ones(self.n_features)
|
|
85
|
+
values = getattr(estimator, "feature_importances_", None)
|
|
86
|
+
coefficients = values is None
|
|
87
|
+
if coefficients:
|
|
88
|
+
values = getattr(estimator, "coef_", None)
|
|
89
|
+
if values is not None:
|
|
90
|
+
try:
|
|
91
|
+
values = np.abs(np.asarray(values, dtype=float))
|
|
92
|
+
except (TypeError, ValueError):
|
|
93
|
+
return np.ones(self.n_features)
|
|
94
|
+
if coefficients and values.ndim == 2:
|
|
95
|
+
values = values.mean(axis=0)
|
|
96
|
+
if values.shape == (self.n_features,) and np.isfinite(values).all():
|
|
97
|
+
return values
|
|
98
|
+
return np.ones(self.n_features)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Read the original model presets from the installed distribution."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
from importlib.resources import files
|
|
5
|
+
from numbers import Integral, Real
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def normalize_sense(value):
|
|
9
|
+
if isinstance(value, str):
|
|
10
|
+
value = value.strip().lower()
|
|
11
|
+
if value in ("max", "maximize", "maximise"):
|
|
12
|
+
return "max"
|
|
13
|
+
if value in ("min", "minimize", "minimise"):
|
|
14
|
+
return "min"
|
|
15
|
+
raise ValueError("sense must be 'max' (maximize) or 'min' (minimize).")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def integer(name, value, minimum):
|
|
19
|
+
if isinstance(value, bool) or not isinstance(value, Integral) or value < minimum:
|
|
20
|
+
raise ValueError(f"{name} must be an integer >= {minimum}.")
|
|
21
|
+
return int(value)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fraction(name, value, *, positive=False):
|
|
25
|
+
if isinstance(value, bool) or not isinstance(value, Real) or not 0 <= value <= 1:
|
|
26
|
+
raise ValueError(f"{name} must be a number between 0 and 1.")
|
|
27
|
+
if positive and value == 0:
|
|
28
|
+
raise ValueError(f"{name} must be positive.")
|
|
29
|
+
return float(value)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parameters(preset, population_size, generations, options):
|
|
33
|
+
with (
|
|
34
|
+
files("fnsga_selector.presets")
|
|
35
|
+
.joinpath("tuned_parameters.csv")
|
|
36
|
+
.open(encoding="utf-8") as stream
|
|
37
|
+
):
|
|
38
|
+
rows = {row.pop(""): row for row in csv.DictReader(stream)}
|
|
39
|
+
if preset not in rows:
|
|
40
|
+
raise ValueError(f"Unknown preset {preset!r}. Choose one of {', '.join(rows)}.")
|
|
41
|
+
params = rows[preset]
|
|
42
|
+
for key, value in params.items():
|
|
43
|
+
params[key] = float(value)
|
|
44
|
+
params["population_size"] = integer("population_size", population_size, 2)
|
|
45
|
+
params["generations"] = integer("generations", generations, 1)
|
|
46
|
+
allowed = set(params) - {"population_size", "generations"}
|
|
47
|
+
if options is not None:
|
|
48
|
+
if not isinstance(options, dict) or not options.keys() <= allowed:
|
|
49
|
+
raise ValueError(f"search_options may contain {sorted(allowed)}.")
|
|
50
|
+
for key, value in options.items():
|
|
51
|
+
params[key] = fraction(key, value, positive=key in {"ls_start", "ls_end"})
|
|
52
|
+
if params["ls_start"] > params["ls_end"]:
|
|
53
|
+
raise ValueError("ls_start must be <= ls_end.")
|
|
54
|
+
return params
|