cc-mapping 0.1.1__tar.gz → 0.2.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.
- cc_mapping-0.2.0/LICENSE +28 -0
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/PKG-INFO +7 -3
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/pyproject.toml +18 -3
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/__init__.py +1 -1
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/core.py +22 -35
- cc_mapping-0.2.0/src/cc_mapping/feature_selection/__init__.py +92 -0
- cc_mapping-0.2.0/src/cc_mapping/feature_selection/_base.py +291 -0
- cc_mapping-0.2.0/src/cc_mapping/feature_selection/_persistence.py +231 -0
- cc_mapping-0.2.0/src/cc_mapping/feature_selection/_plotting.py +191 -0
- cc_mapping-0.2.0/src/cc_mapping/feature_selection/_preprocessing.py +334 -0
- cc_mapping-0.2.0/src/cc_mapping/feature_selection/_random_forest.py +540 -0
- cc_mapping-0.2.0/src/cc_mapping/feature_selection/_training.py +149 -0
- cc_mapping-0.2.0/src/cc_mapping/manifold.py +504 -0
- cc_mapping-0.2.0/src/cc_mapping/plot.py +560 -0
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/preprocess.py +29 -8
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/thresholding/base.py +320 -243
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/thresholding/single.py +248 -167
- cc_mapping-0.1.1/LICENSE +0 -19
- cc_mapping-0.1.1/src/cc_mapping/manifold.py +0 -314
- cc_mapping-0.1.1/src/cc_mapping/plot.py +0 -495
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/README.md +0 -0
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/pseudotime.py +0 -0
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/thresholding/__init__.py +0 -0
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/thresholding/sequential.py +0 -0
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/utils.py +0 -0
- {cc_mapping-0.1.1 → cc_mapping-0.2.0}/src/cc_mapping/utils_v0.py +0 -0
cc_mapping-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025, StallaertLab
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -1,30 +1,34 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: cc-mapping
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Gaussian Mixture Model-based thresholding for single-cell gene expression analysis
|
|
5
5
|
Home-page: https://github.com/StallaertLab/cc_mapping
|
|
6
|
-
License:
|
|
6
|
+
License: BSD-3-Clause
|
|
7
7
|
Keywords: single-cell,gaussian-mixture-model,thresholding,gene-expression,cell-cycle,anndata,bioinformatics,computational-biology
|
|
8
8
|
Author: ddpoe
|
|
9
9
|
Author-email: dap182@pitt.edu
|
|
10
10
|
Requires-Python: >=3.10,<4.0
|
|
11
11
|
Classifier: Development Status :: 4 - Beta
|
|
12
12
|
Classifier: Intended Audience :: Science/Research
|
|
13
|
-
Classifier: License :: OSI Approved ::
|
|
13
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
14
14
|
Classifier: Programming Language :: Python :: 3
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.10
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.11
|
|
17
17
|
Classifier: Programming Language :: Python :: 3.12
|
|
18
18
|
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
19
|
+
Provides-Extra: manifold
|
|
19
20
|
Requires-Dist: anndata (>=0.10.0,<0.11.0)
|
|
20
21
|
Requires-Dist: kneed (>=0.8.5,<0.9.0)
|
|
21
22
|
Requires-Dist: matplotlib (>=3.7.0,<4.0.0)
|
|
22
23
|
Requires-Dist: mpl-scatter-density (>=0.8,<0.9)
|
|
23
24
|
Requires-Dist: numpy (>=1.24.0)
|
|
24
25
|
Requires-Dist: pandas (>=2.0.0,<3.0.0)
|
|
26
|
+
Requires-Dist: phate (>=1.0.0,<2.0.0) ; extra == "manifold"
|
|
25
27
|
Requires-Dist: pydantic (>=2.10.0,<3.0.0)
|
|
26
28
|
Requires-Dist: scikit-learn (>=1.3.0,<2.0.0)
|
|
27
29
|
Requires-Dist: scipy (>=1.11.0,<2.0.0)
|
|
30
|
+
Requires-Dist: skops (>=0.13.0,<0.14.0)
|
|
31
|
+
Requires-Dist: tqdm (>=4.67.1,<5.0.0)
|
|
28
32
|
Project-URL: Documentation, https://cc-mapping.readthedocs.io
|
|
29
33
|
Project-URL: Repository, https://github.com/StallaertLab/cc_mapping
|
|
30
34
|
Description-Content-Type: text/markdown
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "cc-mapping"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.2.0"
|
|
4
4
|
description = "Gaussian Mixture Model-based thresholding for single-cell gene expression analysis"
|
|
5
5
|
authors = ["ddpoe <dap182@pitt.edu>"]
|
|
6
6
|
readme = "README.md"
|
|
7
7
|
packages = [{include = "cc_mapping", from = "src"}]
|
|
8
|
-
license = "
|
|
8
|
+
license = "BSD-3-Clause"
|
|
9
9
|
homepage = "https://github.com/StallaertLab/cc_mapping"
|
|
10
10
|
repository = "https://github.com/StallaertLab/cc_mapping"
|
|
11
11
|
documentation = "https://cc-mapping.readthedocs.io"
|
|
@@ -23,7 +23,7 @@ classifiers = [
|
|
|
23
23
|
"Development Status :: 4 - Beta",
|
|
24
24
|
"Intended Audience :: Science/Research",
|
|
25
25
|
"Topic :: Scientific/Engineering :: Bio-Informatics",
|
|
26
|
-
"License :: OSI Approved ::
|
|
26
|
+
"License :: OSI Approved :: BSD License",
|
|
27
27
|
"Programming Language :: Python :: 3",
|
|
28
28
|
"Programming Language :: Python :: 3.10",
|
|
29
29
|
"Programming Language :: Python :: 3.11",
|
|
@@ -41,6 +41,12 @@ anndata = "^0.10.0"
|
|
|
41
41
|
pydantic = "^2.10.0"
|
|
42
42
|
kneed = "^0.8.5"
|
|
43
43
|
mpl-scatter-density = "^0.8"
|
|
44
|
+
tqdm = "^4.67.1"
|
|
45
|
+
skops = {version = "^0.13.0", optional = true}
|
|
46
|
+
phate = {version = "^1.0.0", optional = true}
|
|
47
|
+
|
|
48
|
+
[tool.poetry.extras]
|
|
49
|
+
manifold = ["phate"]
|
|
44
50
|
|
|
45
51
|
[tool.poetry.group.test.dependencies]
|
|
46
52
|
pytest = "^8.3.5"
|
|
@@ -63,6 +69,15 @@ pydata-sphinx-theme = "^0.16.1"
|
|
|
63
69
|
numpydoc = "^1.9.0"
|
|
64
70
|
myst-nb = "^1.3.0"
|
|
65
71
|
|
|
72
|
+
|
|
73
|
+
[tool.poetry.group.dev.dependencies]
|
|
74
|
+
pre-commit = "^4.5.1"
|
|
75
|
+
|
|
76
|
+
[tool.mypy]
|
|
77
|
+
explicit_package_bases = true
|
|
78
|
+
mypy_path = "src"
|
|
79
|
+
ignore_missing_imports = true
|
|
80
|
+
|
|
66
81
|
[tool.pytest.ini_options]
|
|
67
82
|
testpaths = ["tests"]
|
|
68
83
|
|
|
@@ -1,30 +1,21 @@
|
|
|
1
1
|
from typing import Optional
|
|
2
|
-
from collections import OrderedDict
|
|
3
2
|
import warnings
|
|
3
|
+
|
|
4
4
|
warnings.simplefilter(action="ignore", category=FutureWarning)
|
|
5
5
|
|
|
6
|
-
import numpy as np
|
|
7
|
-
np.seterr(all="ignore")
|
|
6
|
+
import numpy as np # noqa: E402
|
|
8
7
|
|
|
9
|
-
|
|
10
|
-
import anndata as ad
|
|
11
|
-
from scipy import stats as st
|
|
12
|
-
from tqdm import tqdm
|
|
8
|
+
np.seterr(all="ignore")
|
|
13
9
|
|
|
14
|
-
import
|
|
15
|
-
import
|
|
16
|
-
import
|
|
17
|
-
from matplotlib import cm
|
|
10
|
+
import re # noqa: E402
|
|
11
|
+
import anndata as ad # noqa: E402
|
|
12
|
+
from tqdm import tqdm # noqa: E402
|
|
18
13
|
|
|
19
|
-
|
|
20
|
-
from sklearn.mixture import GaussianMixture
|
|
21
|
-
from sklearn import metrics
|
|
22
|
-
from sklearn.preprocessing import LabelEncoder
|
|
23
|
-
from sklearn.model_selection import train_test_split
|
|
24
|
-
from sklearn.ensemble import RandomForestClassifier
|
|
14
|
+
import matplotlib.pyplot as plt # noqa: E402
|
|
25
15
|
|
|
26
|
-
from
|
|
27
|
-
from .
|
|
16
|
+
from sklearn import metrics # noqa: E402
|
|
17
|
+
from sklearn.model_selection import train_test_split # noqa: E402
|
|
18
|
+
from sklearn.ensemble import RandomForestClassifier # noqa: E402
|
|
28
19
|
|
|
29
20
|
|
|
30
21
|
def train_random_forest_model(
|
|
@@ -63,7 +54,9 @@ def train_random_forest_model(
|
|
|
63
54
|
accuracy = metrics.accuracy_score(test_labels, rf_pred_labels)
|
|
64
55
|
|
|
65
56
|
if verbose:
|
|
66
|
-
print(
|
|
57
|
+
print(
|
|
58
|
+
f"Classification Report for RF model trained with {feature_set_description} feature set"
|
|
59
|
+
)
|
|
67
60
|
print("##################################################################")
|
|
68
61
|
print()
|
|
69
62
|
print(metrics.classification_report(test_labels, rf_pred_labels))
|
|
@@ -119,7 +112,7 @@ def random_forest_feature_selection(
|
|
|
119
112
|
verbose: bool = True,
|
|
120
113
|
save_path: str = None,
|
|
121
114
|
cutoff_method: str = "increment",
|
|
122
|
-
train_test_split_params: Optional[dict]=
|
|
115
|
+
train_test_split_params: Optional[dict] = None,
|
|
123
116
|
rf_params: Optional[dict] = None,
|
|
124
117
|
) -> ad.AnnData:
|
|
125
118
|
"""
|
|
@@ -148,7 +141,8 @@ def random_forest_feature_selection(
|
|
|
148
141
|
"""
|
|
149
142
|
|
|
150
143
|
if rf_params is None:
|
|
151
|
-
rf_params = {
|
|
144
|
+
rf_params = {
|
|
145
|
+
"min_samples_leaf": 50,
|
|
152
146
|
"n_estimators": 150,
|
|
153
147
|
"bootstrap": True,
|
|
154
148
|
"oob_score": True,
|
|
@@ -161,14 +155,14 @@ def random_forest_feature_selection(
|
|
|
161
155
|
feature_set_name = f"{method}_feature_set"
|
|
162
156
|
|
|
163
157
|
# Get the indices of the features in the training feature set
|
|
164
|
-
feature_set_idxs
|
|
158
|
+
feature_set_idxs = np.where(np.isin(adata.var_names.values, training_feature_set))[
|
|
159
|
+
0
|
|
160
|
+
]
|
|
165
161
|
|
|
166
162
|
# remove the nan values from the feature set
|
|
167
163
|
# TODO: I need to make this more generalizable because there are other forms of nan in the data
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
except KeyError:
|
|
171
|
-
phase_nan_idx = []
|
|
164
|
+
phase_nan_mask = adata.obs[training_labels].astype(str) == "nan"
|
|
165
|
+
phase_nan_idx = np.where(phase_nan_mask)[0]
|
|
172
166
|
|
|
173
167
|
# isolates the feature set from the adata object
|
|
174
168
|
feature_set = adata.X[:, feature_set_idxs].copy()
|
|
@@ -208,7 +202,6 @@ def random_forest_feature_selection(
|
|
|
208
202
|
optimum_random_forest_feature_set = sorted_feature_set[:optim_feat_num]
|
|
209
203
|
|
|
210
204
|
elif method == "RF_min_max":
|
|
211
|
-
|
|
212
205
|
counter = 0
|
|
213
206
|
max_acc_arg = 0
|
|
214
207
|
acc_list = [0]
|
|
@@ -218,7 +211,6 @@ def random_forest_feature_selection(
|
|
|
218
211
|
desc=f"Training RF model iteratively using most important RF features until {stable_counter} stable iterations",
|
|
219
212
|
disable=not verbose,
|
|
220
213
|
):
|
|
221
|
-
|
|
222
214
|
if counter > stable_counter:
|
|
223
215
|
break
|
|
224
216
|
|
|
@@ -247,7 +239,6 @@ def random_forest_feature_selection(
|
|
|
247
239
|
# and the number of features is greater than 1 (to avoid the 0th index in the accuracy list)
|
|
248
240
|
# elif acc_difference > threshold and num_feats > 1:
|
|
249
241
|
elif acc_difference > threshold:
|
|
250
|
-
|
|
251
242
|
# if the cuttoff method is jump, then if the difference is greater than the threshold,
|
|
252
243
|
# then set the maximum accuracy argument to the current number of features and reset counter
|
|
253
244
|
if cutoff_method == "jump":
|
|
@@ -258,7 +249,6 @@ def random_forest_feature_selection(
|
|
|
258
249
|
# then the optimal number of features is increased by 1 and the check occurs again until the condition is not met
|
|
259
250
|
# when the acc_diccerece is less than the threshold, the counter also decreased by 1
|
|
260
251
|
elif cutoff_method == "increment":
|
|
261
|
-
|
|
262
252
|
temp_max_acc_arg, temp_counter = max_acc_arg, counter
|
|
263
253
|
for _ in range(stable_counter):
|
|
264
254
|
temp_max_acc_arg, temp_counter, continue_bool = (
|
|
@@ -310,9 +300,7 @@ def random_forest_feature_selection(
|
|
|
310
300
|
print(optimum_random_forest_feature_set)
|
|
311
301
|
|
|
312
302
|
# converts the optimal feature set to a boolean array
|
|
313
|
-
|
|
314
|
-
fs_bool = np.repeat(False, adata.shape[1])
|
|
315
|
-
fs_bool[feat_idxs] = True
|
|
303
|
+
fs_bool = np.isin(adata.var_names.values, optimum_random_forest_feature_set)
|
|
316
304
|
|
|
317
305
|
adata.var[feature_set_name] = fs_bool
|
|
318
306
|
|
|
@@ -357,4 +345,3 @@ def random_forest_feature_selection(
|
|
|
357
345
|
plt.close()
|
|
358
346
|
|
|
359
347
|
return adata
|
|
360
|
-
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Feature selection methods for cell cycle mapping.
|
|
3
|
+
|
|
4
|
+
This module provides modular, scikit-learn-style feature selectors
|
|
5
|
+
for identifying informative features from high-dimensional cell data.
|
|
6
|
+
|
|
7
|
+
Classes
|
|
8
|
+
-------
|
|
9
|
+
FeatureSelector
|
|
10
|
+
Abstract base class for all feature selectors.
|
|
11
|
+
RFTopNSelector
|
|
12
|
+
Select top N features by Random Forest importance.
|
|
13
|
+
RFMinMaxSelector
|
|
14
|
+
Find minimum features that maximize classification accuracy.
|
|
15
|
+
|
|
16
|
+
Functions
|
|
17
|
+
---------
|
|
18
|
+
prepare_feature_matrix
|
|
19
|
+
Extract and validate feature matrix from AnnData.
|
|
20
|
+
validate_data
|
|
21
|
+
Validate data is ready for feature selection.
|
|
22
|
+
|
|
23
|
+
Data Classes
|
|
24
|
+
------------
|
|
25
|
+
SelectionResult
|
|
26
|
+
Container for feature selection results.
|
|
27
|
+
PreparedData
|
|
28
|
+
Container for prepared feature matrix and metadata.
|
|
29
|
+
|
|
30
|
+
Examples
|
|
31
|
+
--------
|
|
32
|
+
Basic usage with numpy arrays:
|
|
33
|
+
|
|
34
|
+
>>> from cc_mapping.feature_selection import RFMinMaxSelector, validate_data
|
|
35
|
+
>>>
|
|
36
|
+
>>> validate_data(X, y, feature_names) # Check for NaN/inf
|
|
37
|
+
>>> selector = RFMinMaxSelector(threshold=0.01)
|
|
38
|
+
>>> selector.fit(X, y, feature_names)
|
|
39
|
+
>>>
|
|
40
|
+
>>> print(f"Selected {selector.results.n_features_selected} features")
|
|
41
|
+
>>> mask = selector.get_support()
|
|
42
|
+
|
|
43
|
+
Usage with AnnData:
|
|
44
|
+
|
|
45
|
+
>>> from cc_mapping.feature_selection import prepare_feature_matrix, RFTopNSelector
|
|
46
|
+
>>>
|
|
47
|
+
>>> prepared = prepare_feature_matrix(
|
|
48
|
+
... adata,
|
|
49
|
+
... feature_set="intensity_features",
|
|
50
|
+
... labels="cell_cycle_phase",
|
|
51
|
+
... )
|
|
52
|
+
>>>
|
|
53
|
+
>>> selector = RFTopNSelector(n_features=30)
|
|
54
|
+
>>> selector.fit(prepared.X, prepared.y, prepared.feature_names)
|
|
55
|
+
>>>
|
|
56
|
+
>>> # Add selection to adata
|
|
57
|
+
>>> adata = selector.transform_adata(adata, var_key="selected_features")
|
|
58
|
+
|
|
59
|
+
Saving and loading:
|
|
60
|
+
|
|
61
|
+
>>> selector.save("my_selector.skops")
|
|
62
|
+
>>> loaded = RFMinMaxSelector.load("my_selector.skops")
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
from ._base import FeatureSelector, SelectionResult
|
|
66
|
+
from ._preprocessing import (
|
|
67
|
+
prepare_feature_matrix,
|
|
68
|
+
validate_data,
|
|
69
|
+
PreparedData,
|
|
70
|
+
)
|
|
71
|
+
from ._random_forest import RFTopNSelector, RFMinMaxSelector
|
|
72
|
+
from ._plotting import plot_accuracy_curve, plot_feature_importances
|
|
73
|
+
from ._training import train_rf_model, TrainingResult
|
|
74
|
+
|
|
75
|
+
__all__ = [
|
|
76
|
+
# Base classes
|
|
77
|
+
"FeatureSelector",
|
|
78
|
+
"SelectionResult",
|
|
79
|
+
# Preprocessing
|
|
80
|
+
"prepare_feature_matrix",
|
|
81
|
+
"validate_data",
|
|
82
|
+
"PreparedData",
|
|
83
|
+
# Selectors
|
|
84
|
+
"RFTopNSelector",
|
|
85
|
+
"RFMinMaxSelector",
|
|
86
|
+
# Plotting
|
|
87
|
+
"plot_accuracy_curve",
|
|
88
|
+
"plot_feature_importances",
|
|
89
|
+
# Training utilities
|
|
90
|
+
"train_rf_model",
|
|
91
|
+
"TrainingResult",
|
|
92
|
+
]
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Base classes and data structures for feature selection.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
import anndata as ad
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from typing_extensions import Self
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class SelectionResult:
|
|
21
|
+
"""
|
|
22
|
+
Container for feature selection results.
|
|
23
|
+
|
|
24
|
+
Attributes
|
|
25
|
+
----------
|
|
26
|
+
selected_features : np.ndarray
|
|
27
|
+
Names of selected features, sorted by importance.
|
|
28
|
+
feature_importances : np.ndarray
|
|
29
|
+
Importance scores for selected features (same order as selected_features).
|
|
30
|
+
n_features_selected : int
|
|
31
|
+
Number of features selected.
|
|
32
|
+
metadata : dict
|
|
33
|
+
Method-specific metadata (e.g., accuracy curve for RF methods).
|
|
34
|
+
"""
|
|
35
|
+
selected_features: np.ndarray
|
|
36
|
+
feature_importances: np.ndarray
|
|
37
|
+
n_features_selected: int
|
|
38
|
+
metadata: dict = field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
def __repr__(self) -> str:
|
|
41
|
+
return (
|
|
42
|
+
f"SelectionResult(n_features={self.n_features_selected}, "
|
|
43
|
+
f"top_features={list(self.selected_features[:3])}...)"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class FeatureSelector(ABC):
|
|
48
|
+
"""
|
|
49
|
+
Abstract base class for feature selection methods.
|
|
50
|
+
|
|
51
|
+
All feature selectors should inherit from this class and implement
|
|
52
|
+
the required abstract methods.
|
|
53
|
+
|
|
54
|
+
Attributes
|
|
55
|
+
----------
|
|
56
|
+
model_ : Any
|
|
57
|
+
The fitted model (e.g., RandomForestClassifier). Available after fit().
|
|
58
|
+
results_ : SelectionResult
|
|
59
|
+
Detailed selection results. Available after fit().
|
|
60
|
+
feature_names_ : np.ndarray
|
|
61
|
+
Feature names used during fitting. Available after fit().
|
|
62
|
+
is_fitted_ : bool
|
|
63
|
+
Whether the selector has been fitted.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
model_: Any = None
|
|
67
|
+
results_: SelectionResult | None = None
|
|
68
|
+
feature_names_: np.ndarray | None = None
|
|
69
|
+
is_fitted_: bool = False
|
|
70
|
+
|
|
71
|
+
@abstractmethod
|
|
72
|
+
def fit(
|
|
73
|
+
self,
|
|
74
|
+
X: np.ndarray,
|
|
75
|
+
y: np.ndarray,
|
|
76
|
+
feature_names: np.ndarray
|
|
77
|
+
) -> Self:
|
|
78
|
+
"""
|
|
79
|
+
Fit the feature selector to the data.
|
|
80
|
+
|
|
81
|
+
Parameters
|
|
82
|
+
----------
|
|
83
|
+
X : np.ndarray
|
|
84
|
+
Feature matrix of shape (n_samples, n_features).
|
|
85
|
+
y : np.ndarray
|
|
86
|
+
Target labels of shape (n_samples,).
|
|
87
|
+
feature_names : np.ndarray
|
|
88
|
+
Names of features corresponding to columns in X.
|
|
89
|
+
|
|
90
|
+
Returns
|
|
91
|
+
-------
|
|
92
|
+
Self
|
|
93
|
+
The fitted selector instance (for method chaining).
|
|
94
|
+
"""
|
|
95
|
+
...
|
|
96
|
+
|
|
97
|
+
def get_support(self, indices: bool = False) -> np.ndarray:
|
|
98
|
+
"""
|
|
99
|
+
Get a mask or indices of selected features.
|
|
100
|
+
|
|
101
|
+
Parameters
|
|
102
|
+
----------
|
|
103
|
+
indices : bool, default=False
|
|
104
|
+
If True, return indices instead of boolean mask.
|
|
105
|
+
|
|
106
|
+
Returns
|
|
107
|
+
-------
|
|
108
|
+
np.ndarray
|
|
109
|
+
Boolean mask of shape (n_features,) or integer indices.
|
|
110
|
+
|
|
111
|
+
Raises
|
|
112
|
+
------
|
|
113
|
+
RuntimeError
|
|
114
|
+
If selector has not been fitted.
|
|
115
|
+
"""
|
|
116
|
+
self._check_is_fitted()
|
|
117
|
+
|
|
118
|
+
# Create boolean mask based on selected features
|
|
119
|
+
mask = np.isin(self.feature_names_, self.results_.selected_features)
|
|
120
|
+
|
|
121
|
+
if indices:
|
|
122
|
+
return np.where(mask)[0]
|
|
123
|
+
return mask
|
|
124
|
+
|
|
125
|
+
def get_feature_names_out(self) -> np.ndarray:
|
|
126
|
+
"""
|
|
127
|
+
Get names of selected features.
|
|
128
|
+
|
|
129
|
+
Returns
|
|
130
|
+
-------
|
|
131
|
+
np.ndarray
|
|
132
|
+
Array of selected feature names.
|
|
133
|
+
|
|
134
|
+
Raises
|
|
135
|
+
------
|
|
136
|
+
RuntimeError
|
|
137
|
+
If selector has not been fitted.
|
|
138
|
+
"""
|
|
139
|
+
self._check_is_fitted()
|
|
140
|
+
return self.results_.selected_features.copy()
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def results(self) -> SelectionResult:
|
|
144
|
+
"""
|
|
145
|
+
Get the selection results.
|
|
146
|
+
|
|
147
|
+
Returns
|
|
148
|
+
-------
|
|
149
|
+
SelectionResult
|
|
150
|
+
Detailed results from feature selection.
|
|
151
|
+
|
|
152
|
+
Raises
|
|
153
|
+
------
|
|
154
|
+
RuntimeError
|
|
155
|
+
If selector has not been fitted.
|
|
156
|
+
"""
|
|
157
|
+
self._check_is_fitted()
|
|
158
|
+
return self.results_
|
|
159
|
+
|
|
160
|
+
def fit_adata(
|
|
161
|
+
self,
|
|
162
|
+
adata: ad.AnnData,
|
|
163
|
+
feature_set_key: str | list[str],
|
|
164
|
+
label_key: str,
|
|
165
|
+
drop_na: bool = True,
|
|
166
|
+
drop_inf: bool = True,
|
|
167
|
+
) -> Self:
|
|
168
|
+
"""
|
|
169
|
+
Convenience method to fit directly from AnnData object.
|
|
170
|
+
|
|
171
|
+
Parameters
|
|
172
|
+
----------
|
|
173
|
+
adata : ad.AnnData
|
|
174
|
+
AnnData object containing the data.
|
|
175
|
+
feature_set_key : str or list[str]
|
|
176
|
+
Either a key in adata.var that marks features (boolean column),
|
|
177
|
+
or a list of feature names.
|
|
178
|
+
label_key : str
|
|
179
|
+
Key in adata.obs containing target labels.
|
|
180
|
+
drop_na : bool, default=True
|
|
181
|
+
Whether to drop rows with NaN values.
|
|
182
|
+
drop_inf : bool, default=True
|
|
183
|
+
Whether to drop rows with infinite values.
|
|
184
|
+
|
|
185
|
+
Returns
|
|
186
|
+
-------
|
|
187
|
+
Self
|
|
188
|
+
The fitted selector instance.
|
|
189
|
+
"""
|
|
190
|
+
# Import here to avoid circular imports
|
|
191
|
+
from ._preprocessing import prepare_feature_matrix
|
|
192
|
+
|
|
193
|
+
prepared = prepare_feature_matrix(
|
|
194
|
+
adata=adata,
|
|
195
|
+
feature_set=feature_set_key,
|
|
196
|
+
labels=label_key,
|
|
197
|
+
drop_na=drop_na,
|
|
198
|
+
drop_inf=drop_inf,
|
|
199
|
+
verbose=getattr(self, 'verbose', True),
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
return self.fit(prepared.X, prepared.y, prepared.feature_names)
|
|
203
|
+
|
|
204
|
+
def transform_adata(
|
|
205
|
+
self,
|
|
206
|
+
adata: ad.AnnData,
|
|
207
|
+
var_key: str = "selected_features",
|
|
208
|
+
) -> ad.AnnData:
|
|
209
|
+
"""
|
|
210
|
+
Add selection mask to adata.var.
|
|
211
|
+
|
|
212
|
+
Parameters
|
|
213
|
+
----------
|
|
214
|
+
adata : ad.AnnData
|
|
215
|
+
AnnData object to modify.
|
|
216
|
+
var_key : str, default="selected_features"
|
|
217
|
+
Key to use in adata.var for the selection mask.
|
|
218
|
+
|
|
219
|
+
Returns
|
|
220
|
+
-------
|
|
221
|
+
ad.AnnData
|
|
222
|
+
Modified AnnData object with selection mask in .var.
|
|
223
|
+
|
|
224
|
+
Raises
|
|
225
|
+
------
|
|
226
|
+
RuntimeError
|
|
227
|
+
If selector has not been fitted.
|
|
228
|
+
"""
|
|
229
|
+
self._check_is_fitted()
|
|
230
|
+
|
|
231
|
+
# Create boolean mask for all features in adata
|
|
232
|
+
mask = np.isin(adata.var_names.values, self.results_.selected_features)
|
|
233
|
+
adata.var[var_key] = mask
|
|
234
|
+
|
|
235
|
+
return adata
|
|
236
|
+
|
|
237
|
+
def save(self, path: str | Path) -> None:
|
|
238
|
+
"""
|
|
239
|
+
Save the fitted selector to disk using skops.
|
|
240
|
+
|
|
241
|
+
Parameters
|
|
242
|
+
----------
|
|
243
|
+
path : str or Path
|
|
244
|
+
File path to save to.
|
|
245
|
+
|
|
246
|
+
Raises
|
|
247
|
+
------
|
|
248
|
+
RuntimeError
|
|
249
|
+
If selector has not been fitted.
|
|
250
|
+
"""
|
|
251
|
+
self._check_is_fitted()
|
|
252
|
+
from ._persistence import save_selector
|
|
253
|
+
save_selector(self, path)
|
|
254
|
+
|
|
255
|
+
@classmethod
|
|
256
|
+
def load(cls, path: str | Path) -> Self:
|
|
257
|
+
"""
|
|
258
|
+
Load a fitted selector from disk.
|
|
259
|
+
|
|
260
|
+
Parameters
|
|
261
|
+
----------
|
|
262
|
+
path : str or Path
|
|
263
|
+
File path to load from.
|
|
264
|
+
|
|
265
|
+
Returns
|
|
266
|
+
-------
|
|
267
|
+
Self
|
|
268
|
+
The loaded selector instance.
|
|
269
|
+
"""
|
|
270
|
+
from ._persistence import load_selector
|
|
271
|
+
return load_selector(path)
|
|
272
|
+
|
|
273
|
+
@abstractmethod
|
|
274
|
+
def get_params(self) -> dict:
|
|
275
|
+
"""
|
|
276
|
+
Get hyperparameters of this selector.
|
|
277
|
+
|
|
278
|
+
Returns
|
|
279
|
+
-------
|
|
280
|
+
dict
|
|
281
|
+
Dictionary of hyperparameter names and values.
|
|
282
|
+
"""
|
|
283
|
+
...
|
|
284
|
+
|
|
285
|
+
def _check_is_fitted(self) -> None:
|
|
286
|
+
"""Raise error if selector is not fitted."""
|
|
287
|
+
if not self.is_fitted_:
|
|
288
|
+
raise RuntimeError(
|
|
289
|
+
f"{self.__class__.__name__} has not been fitted. "
|
|
290
|
+
"Call fit() or fit_adata() first."
|
|
291
|
+
)
|