pymutualinfo 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.
Files changed (51) hide show
  1. pymutualinfo-0.2.0/CHANGELOG.md +166 -0
  2. pymutualinfo-0.2.0/LICENSE +28 -0
  3. pymutualinfo-0.2.0/MANIFEST.in +7 -0
  4. pymutualinfo-0.2.0/PKG-INFO +170 -0
  5. pymutualinfo-0.2.0/README.md +132 -0
  6. pymutualinfo-0.2.0/docs/encoding.md +41 -0
  7. pymutualinfo-0.2.0/docs/feature_selection.md +142 -0
  8. pymutualinfo-0.2.0/docs/mutual_information.md +205 -0
  9. pymutualinfo-0.2.0/docs/releasing.md +54 -0
  10. pymutualinfo-0.2.0/docs/utils.md +41 -0
  11. pymutualinfo-0.2.0/fast_mi/__init__.py +36 -0
  12. pymutualinfo-0.2.0/fast_mi/binning.py +7 -0
  13. pymutualinfo-0.2.0/fast_mi/encoding.py +7 -0
  14. pymutualinfo-0.2.0/fast_mi/feature_selection.py +7 -0
  15. pymutualinfo-0.2.0/fast_mi/mutual_information.py +7 -0
  16. pymutualinfo-0.2.0/fast_mi/sklearn.py +7 -0
  17. pymutualinfo-0.2.0/fast_mi/utils.py +7 -0
  18. pymutualinfo-0.2.0/fastmi/__init__.py +50 -0
  19. pymutualinfo-0.2.0/fastmi/binning.py +263 -0
  20. pymutualinfo-0.2.0/fastmi/encoding.py +62 -0
  21. pymutualinfo-0.2.0/fastmi/feature_selection.py +392 -0
  22. pymutualinfo-0.2.0/fastmi/mutual_information.py +1055 -0
  23. pymutualinfo-0.2.0/fastmi/sklearn.py +233 -0
  24. pymutualinfo-0.2.0/fastmi/utils.py +108 -0
  25. pymutualinfo-0.2.0/pymutualinfo.egg-info/PKG-INFO +170 -0
  26. pymutualinfo-0.2.0/pymutualinfo.egg-info/SOURCES.txt +49 -0
  27. pymutualinfo-0.2.0/pymutualinfo.egg-info/dependency_links.txt +1 -0
  28. pymutualinfo-0.2.0/pymutualinfo.egg-info/requires.txt +10 -0
  29. pymutualinfo-0.2.0/pymutualinfo.egg-info/top_level.txt +2 -0
  30. pymutualinfo-0.2.0/pyproject.toml +61 -0
  31. pymutualinfo-0.2.0/setup.cfg +4 -0
  32. pymutualinfo-0.2.0/tests/test_accurate_bins.py +30 -0
  33. pymutualinfo-0.2.0/tests/test_auto_correction.py +74 -0
  34. pymutualinfo-0.2.0/tests/test_binning.py +335 -0
  35. pymutualinfo-0.2.0/tests/test_compat.py +47 -0
  36. pymutualinfo-0.2.0/tests/test_correctness.py +119 -0
  37. pymutualinfo-0.2.0/tests/test_encoding.py +52 -0
  38. pymutualinfo-0.2.0/tests/test_feature_selection.py +164 -0
  39. pymutualinfo-0.2.0/tests/test_integer_views.py +78 -0
  40. pymutualinfo-0.2.0/tests/test_interactions.py +68 -0
  41. pymutualinfo-0.2.0/tests/test_missing_values.py +83 -0
  42. pymutualinfo-0.2.0/tests/test_mrmr.py +51 -0
  43. pymutualinfo-0.2.0/tests/test_mutual_information.py +94 -0
  44. pymutualinfo-0.2.0/tests/test_properties.py +73 -0
  45. pymutualinfo-0.2.0/tests/test_random_state.py +81 -0
  46. pymutualinfo-0.2.0/tests/test_scores.py +56 -0
  47. pymutualinfo-0.2.0/tests/test_sklearn_selectors.py +110 -0
  48. pymutualinfo-0.2.0/tests/test_speed.py +75 -0
  49. pymutualinfo-0.2.0/tests/test_targets.py +69 -0
  50. pymutualinfo-0.2.0/tests/test_utils.py +81 -0
  51. pymutualinfo-0.2.0/tests/test_validation.py +91 -0
@@ -0,0 +1,166 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (2026-12-04)
4
+
5
+ First public release, published on PyPI as `fastmi`. Highlights since 0.1.0:
6
+
7
+ - **Renamed to `fastmi`.** The distribution and the import package are now
8
+ `fastmi`, and the repository moved to `github.com/calebdame/pymutualinfo` (the old
9
+ URL redirects). `import fast_mi` and `from fast_mi.<module> import ...` keep
10
+ working through a deprecated alias that emits a `DeprecationWarning`; it will
11
+ be removed in a future release.
12
+ - **Licensed under the BSD 3-Clause license.**
13
+ - **New default estimator** (equal-frequency bins on ranks with a common bin
14
+ count, plus an automatic bias correction). Spearman correlation with the true
15
+ MI order rises from 0.58 to 0.85 and precision@k from 0.69 to 0.90 on 800
16
+ benchmark datasets, and scoring is about 2x faster. Scores differ from 0.1.0;
17
+ `binning="fd", bias_correction="shuffle"` reproduces them.
18
+ - **Audit fixes**: NaN and inf handling, `target_type` in the rankers, string
19
+ class labels, large integer IDs, CMIM/JMI joint variables, input validation.
20
+ - **New features**: estimator options (`binning`, `n_bins`, `bias_correction`,
21
+ `discrete_features`), `n_bins="accurate"` for absolute MI values, automatic
22
+ categorical/ordinal views of integer columns, `random_state`,
23
+ `pairwise_interaction_information`, scikit-learn feature-name support.
24
+ - **Performance**: shared code matrices for pairwise MI, incremental CMIM,
25
+ lazy imports, faster counting and factorisation.
26
+ - **Packaging**: project metadata and URLs, a tag-triggered release workflow
27
+ with PyPI trusted publishing, and a lean distribution (the research and
28
+ benchmark code is not included).
29
+
30
+ The details follow.
31
+
32
+ ### Renamed
33
+
34
+ - The package is now `fastmi` (`pip install fastmi`, `import fastmi`).
35
+ `fast_mi` remains as a deprecated alias: it re-exports the public API, maps
36
+ every submodule (`fast_mi.mutual_information`, `fast_mi.sklearn`, ...) to
37
+ its `fastmi` module and emits a `DeprecationWarning` on import.
38
+ - `fastmi.__version__` reports the installed version.
39
+
40
+ ### License
41
+
42
+ - Released under the BSD 3-Clause license (`LICENSE`).
43
+
44
+ ### Added
45
+
46
+ - `n_bins="accurate"`: finer bins (`ceil(n^(1/3))` below 1000 rows,
47
+ `ceil(2 n^(1/3))` above) for absolute MI values rather than rankings. At
48
+ n=5000 the RMSE against exact MI is 0.009, versus 0.044 for the ranking
49
+ default, at the same speed.
50
+ - The sklearn selectors set `n_features_in_` and `feature_names_in_` and provide
51
+ `get_feature_names_out`, so `set_output(transform="pandas")` works. `transform`
52
+ checks the number of features. When CMIM thresholds leave fewer features than
53
+ `k_features`, `fit` now warns and caps `k_features_`.
54
+ - A `random_state` argument on every public function and selector, for
55
+ reproducible row sampling with `sample < 1`.
56
+ - `pairwise_interaction_information` returns the interaction information
57
+ `I(X_i, X_j; Y) - I(X_i; Y) - I(X_j; Y)` of every feature pair, so pure
58
+ interactions such as XOR, which have no marginal MI, can be screened.
59
+
60
+ - Estimator options on every function and selector: `binning` (Freedman-Diaconis,
61
+ NumPy's equal-width rules, MAD/Qn widths, Knuth, Shimazaki-Shinomoto, uniform,
62
+ `quantile`, `hybrid`, `none`), `n_bins` and `bias_correction` (`shuffle`,
63
+ `shuffle_mean`, `miller_madow`, `auto`, `expected`, `grassberger`, `chao_shen`,
64
+ `jackknife`, `none`). `discrete_features` marks columns whose values are
65
+ categories and must never be binned. See `research/BINNING.md`.
66
+
67
+ ### Breaking changes
68
+
69
+ - New default estimator: equal-frequency ("hybrid") bins on ranks with
70
+ `ceil(n ** (1/3) / 2)` bins per column, where values repeated at least
71
+ `n / n_bins` times get a bin of their own, plus the `auto` bias correction:
72
+ Miller-Madow on well-filled tables, the mean of 10 permutations on sparse
73
+ ones, and a linear blend between 3 and 8 rows per occupied cell. A hard switch
74
+ flipped between two estimates with opposite biases near its threshold. The old
75
+ Freedman-Diaconis rule returned raw values whenever it asked for at least as
76
+ many bins as distinct values, which scored heavy-tailed, zero-inflated and
77
+ high-cardinality integer features as about 0. Its bin counts also depended on
78
+ each column's shape. On the benchmark in `research/`, Spearman correlation with
79
+ the true MI order rises from 0.58 to 0.85, precision@k from 0.69 to 0.90, and
80
+ scoring is about 2x faster. Scores change for all continuous features and are
81
+ lower for strong dependence, because the bins are coarser. Rankings change
82
+ wherever features differ in shape. `binning="fd", bias_correction="shuffle"`
83
+ restores the previous behaviour exactly.
84
+ - Integer-valued columns with at most 32 distinct values are used as
85
+ categories. A column with more may be ordinal (counts, amounts) or nominal
86
+ (codes, IDs). With the default `discrete_features="auto"`, each such column
87
+ uses whichever view has the larger bias-corrected MI with the target: its
88
+ values as categories, or rank bins. Pairwise MI chooses per pair. Non-numeric
89
+ columns encoded with `encoding=` are always used as categories. An explicit
90
+ `discrete_features` turns the choice off; integer columns it does not list
91
+ are then binned. The choice is only made with corrections that handle sparse
92
+ tables (`auto` and the permutation corrections).
93
+
94
+ - `select_features_by_cmim` and `CMIMSelector` no longer accept `early_stopping`.
95
+ Scores are now updated incrementally, which already skips the work early stopping
96
+ used to avoid.
97
+ - Removed `fast_mi.feature_selection_legacy`. Nothing in the package used it.
98
+ - MI scores change slightly, and are more accurate, because `discretize` changed:
99
+ - Binning is deterministic. Results used to depend on the global NumPy random
100
+ state.
101
+ - Bins follow `np.histogram` exactly.
102
+ - Continuous columns with a large magnitude (above about 1e5) or a tiny scale are
103
+ now binned. Before, every distinct value became its own category, which inflated
104
+ their scores.
105
+ - Rankings on typical data are stable, but stored scores from earlier versions are
106
+ not directly comparable.
107
+
108
+ - mRMR, CMIM and JMI now honour `target_type`. With the default
109
+ (`"binary"`) or `"classification"`, the target is used as class labels
110
+ as-is. Previously it was always discretised as if it were continuous.
111
+ Continuous targets therefore need `target_type="continuous"` or
112
+ `"regression"`. A `UserWarning` flags non-integer float targets that are
113
+ given a discrete `target_type`.
114
+
115
+ - MI scores from `select_features_by_mutual_information` and
116
+ `pairwise_mutual_information`, and the `relevance`/`redundancy` returned by the
117
+ rankers, are now clipped at 0. Rankings still use the unclipped estimates.
118
+ - `+inf` and `-inf` in features are now treated as missing, grouped with NaN,
119
+ and a `UserWarning` names the affected columns. Before, any column containing an
120
+ inf silently scored 0.
121
+
122
+ ### Fixed
123
+
124
+ - mRMR, CMIM and JMI accept string and categorical class labels.
125
+
126
+ - Features are now converted to `float64` instead of `float32`. Integer columns
127
+ above 2**24, such as large IDs, are no longer merged by rounding. Internal
128
+ feature arrays use twice the memory.
129
+ - Any NaN in a feature crashed `pairwise_mutual_information`, mRMR, CMIM and JMI.
130
+ NaN is now treated as its own category.
131
+ - CMIM and JMI joint variables were corrupted for negative or non-integer labels
132
+ (`_encode_pair` collisions).
133
+ - `discretize` failed or ran out of memory on columns whose IQR is tiny relative to
134
+ their range.
135
+ - Counting a joint table of two high-cardinality columns could allocate a huge dense
136
+ table.
137
+ - `encode_features` no longer mutates its input. It also no longer label-encodes
138
+ numeric columns stored as `object`.
139
+ - Invalid `target_type`, missing target values, 1-D features, empty input and invalid
140
+ `n_jobs` now raise clear `ValueError`s. `n_jobs=-1` uses at least one worker.
141
+
142
+ ### Performance
143
+
144
+ - Small-range integer labels are factorised with `bincount` instead of
145
+ `np.unique` (3x faster for that step); scores are 10-15% faster.
146
+ - `pairwise_mutual_information`, mRMR, CMIM and JMI compute pairwise MI from one
147
+ shared int32 code matrix instead of sending four float columns per pair to
148
+ the workers. mRMR at n=1e5, p=30 takes 0.50 s serially (was 1.02 s) and
149
+ 0.22 s with 8 processes (was 0.66 s).
150
+ - scikit-learn and SciPy are imported lazily, and the selectors are loaded on
151
+ first access. `import fastmi` takes 0.19 s instead of 0.40 s.
152
+ - Joint counts use `np.bincount` instead of `np.histogram2d`, about 4.5x faster.
153
+ - CMIM updates its scores incrementally, about 20x faster at p=30.
154
+ - Pairwise MI reuses discretised columns, about 2x faster.
155
+ - Removed the redundant `Counter`-based log-probability dictionaries, which were
156
+ built with a Python loop over every row. JMI factorises each column once instead
157
+ of once per pair. At n=1e5, p=10: JMI is 27% faster, CMIM 23% and pairwise MI 17%.
158
+ Output is identical.
159
+ - Missing values use integer codes instead of a `"NaN"` string label, about 3x
160
+ faster on columns with NaNs. Scores are identical.
161
+
162
+ ## 0.1.0
163
+
164
+ - Initial version: histogram mutual information with a shuffle bias
165
+ correction, pairwise MI, mRMR, CMIM and JMI rankers, label and frequency
166
+ encoding, and scikit-learn selectors. Not published on PyPI.
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Caleb Dame
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.
@@ -0,0 +1,7 @@
1
+ # The sdist carries the package, tests, docs and changelog. The research and
2
+ # benchmark code (and its result files) stay in the repository only.
3
+ include CHANGELOG.md
4
+ graft docs
5
+ prune research
6
+ prune benchmarks
7
+ global-exclude *.py[cod]
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.4
2
+ Name: pymutualinfo
3
+ Version: 0.2.0
4
+ Summary: Fast mutual information estimation and MI-based feature selection (mRMR, CMIM, JMI) for tabular data
5
+ Author: Caleb Dame
6
+ License-Expression: BSD-3-Clause
7
+ Project-URL: Homepage, https://github.com/calebdame/pymutualinfo
8
+ Project-URL: Repository, https://github.com/calebdame/pymutualinfo
9
+ Project-URL: Documentation, https://github.com/calebdame/pymutualinfo/tree/main/docs
10
+ Project-URL: Changelog, https://github.com/calebdame/pymutualinfo/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/calebdame/pymutualinfo/issues
12
+ Keywords: mutual information,feature selection,mrmr,cmim,jmi,information theory,scikit-learn,pandas
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: numpy>=1.22
29
+ Requires-Dist: pandas>=1.5
30
+ Requires-Dist: scikit-learn>=1.1
31
+ Requires-Dist: joblib>=1.1
32
+ Requires-Dist: tqdm>=4.0
33
+ Provides-Extra: test
34
+ Requires-Dist: pytest>=7; extra == "test"
35
+ Requires-Dist: pytest-cov; extra == "test"
36
+ Requires-Dist: hypothesis>=6; extra == "test"
37
+ Dynamic: license-file
38
+
39
+ # pymutualinfo
40
+
41
+ [![License: BSD-3-Clause](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](https://github.com/calebdame/pymutualinfo/blob/main/LICENSE)
42
+
43
+ Fast, accurate mutual information for ranking and selecting features in tabular data,
44
+ with redundancy-aware selectors (mRMR, CMIM, JMI) and native support for NaN and
45
+ string columns.
46
+
47
+ ## Install
48
+
49
+ ```bash
50
+ pip install pymutualinfo
51
+ ```
52
+
53
+ The package imports as `fastmi`:
54
+
55
+ ```python
56
+ import fastmi
57
+ ```
58
+
59
+ Requires Python 3.10 or newer. Dependencies: NumPy, pandas, scikit-learn, joblib and
60
+ tqdm.
61
+
62
+ ## Quick start
63
+
64
+ ```python
65
+ from fastmi import select_features_by_mutual_information, select_features_by_mrmr
66
+
67
+ scores = select_features_by_mutual_information(X, y, target_type="binary") # MI per column, in nats
68
+ order = select_features_by_mrmr(X, y, target_type="binary") # column indices, best first
69
+ ```
70
+
71
+ `X` is a pandas DataFrame or a 2-D NumPy array and `y` the target. Use
72
+ `target_type="classification"` for multiclass labels and `"continuous"` for regression
73
+ targets.
74
+
75
+ ## Why pymutualinfo
76
+
77
+ **Better rankings than scikit-learn's KSG estimator.** On 800 synthetic datasets with
78
+ exact ground-truth MI (heavy tails, skew, point masses, integer columns, weak and strong
79
+ signals), the default estimator orders features much closer to the true order:
80
+
81
+ | Estimator | Spearman with true MI order | Precision@k |
82
+ |---|---|---|
83
+ | **fastmi (default)** | **0.85** | **0.90** |
84
+ | scikit-learn KSG (`mutual_info_classif` / `mutual_info_regression`) | 0.67 | 0.74 |
85
+ | scikit-learn KSG on rank-transformed columns | 0.68 | 0.75 |
86
+ | fastmi 0.1 (Freedman-Diaconis bins) | 0.58 | 0.69 |
87
+
88
+ **Much faster.** Single process unless noted:
89
+
90
+ | Case | Speed-up over scikit-learn |
91
+ |---|---|
92
+ | Continuous features, n = 1e3 to 1e6 | 9-31x |
93
+ | Default scoring, p = 50, n = 2e4 | about 50x (0.04 s vs 2.15 s) |
94
+ | n = 1e6, p = 100, 8 processes on both sides | 18x (1.9 s vs 35 s) |
95
+ | Continuous target, low-cardinality integer features | 45-55x |
96
+ | Continuous target, high-cardinality (ID-like) integer features, n = 1e4 | about 900x (0.006 s vs 5.5 s) |
97
+
98
+ **Takes real-world data as is.** NaN forms its own category, string and categorical
99
+ columns are encoded for you (`encoding="label"` or `"frequency"`), and integer columns
100
+ are treated as categories or as ordinal values, whichever carries more information.
101
+ scikit-learn's estimators accept neither NaN nor strings.
102
+
103
+ **Selects features, not just scores them.** mRMR, CMIM and JMI penalise redundancy, so
104
+ near-duplicate columns do not crowd out independent signals.
105
+ `pairwise_interaction_information` screens for pairs, such as XOR, that are informative
106
+ only together.
107
+
108
+ The full results and the commands that reproduce them are in
109
+ [benchmarks/RESULTS.md](https://github.com/calebdame/pymutualinfo/blob/main/benchmarks/RESULTS.md)
110
+ (speed and selection against scikit-learn) and
111
+ [research/BINNING.md](https://github.com/calebdame/pymutualinfo/blob/main/research/BINNING.md)
112
+ (estimator study: ranking quality, absolute error, speed).
113
+
114
+ ## scikit-learn pipelines
115
+
116
+ `FastMISelector`, `MRMRSelector`, `CMIMSelector` and `JMISelector` are scikit-learn
117
+ transformers:
118
+
119
+ ```python
120
+ from sklearn.linear_model import LogisticRegression
121
+ from sklearn.pipeline import Pipeline
122
+ from fastmi import CMIMSelector
123
+
124
+ pipe = Pipeline([
125
+ ("select", CMIMSelector(k_features=20, target_type="binary")),
126
+ ("model", LogisticRegression()),
127
+ ])
128
+ pipe.fit(X, y)
129
+ ```
130
+
131
+ They support `get_feature_names_out` and `set_output(transform="pandas")`.
132
+
133
+ ## Choosing settings
134
+
135
+ The defaults are tuned for ranking and selecting features. For accurate absolute MI
136
+ values at n >= 5000, use `n_bins="accurate"`. For small samples with very strong
137
+ dependence, a kNN estimator on ranks is more accurate. The
138
+ [settings-by-goal table](https://github.com/calebdame/pymutualinfo/blob/main/docs/mutual_information.md#which-settings-for-which-goal)
139
+ covers these cases and the binning, bias-correction and integer-column options.
140
+
141
+ ## Documentation
142
+
143
+ - [Mutual information](https://github.com/calebdame/pymutualinfo/blob/main/docs/mutual_information.md):
144
+ `select_features_by_mutual_information`, `pairwise_mutual_information`,
145
+ `select_features_by_mrmr` and the estimator options.
146
+ - [Feature selection](https://github.com/calebdame/pymutualinfo/blob/main/docs/feature_selection.md):
147
+ CMIM, JMI, interaction information and the scikit-learn selectors.
148
+ - [Encoding](https://github.com/calebdame/pymutualinfo/blob/main/docs/encoding.md) and
149
+ [utilities](https://github.com/calebdame/pymutualinfo/blob/main/docs/utils.md).
150
+ - [Changelog](https://github.com/calebdame/pymutualinfo/blob/main/CHANGELOG.md).
151
+
152
+ ## Leak-free modeling
153
+
154
+ Selecting features on the full dataset and then evaluating on the same rows overstates
155
+ performance. The companion package
156
+ [outofsample](https://github.com/calebdame/outofsample) (`pip install outofsample`)
157
+ wraps scikit-learn estimators and pipelines, including a fastmi selector step, so that
158
+ every row is predicted by a model that never saw it.
159
+
160
+ ## Migrating from `fast_mi`
161
+
162
+ The package was called `fast_mi` before 0.2.0. `import fast_mi` still works but emits a
163
+ `DeprecationWarning`; replace it with `import fastmi`. Version 0.2.0 also changes the
164
+ default estimator, so scores differ from 0.1.0; `binning="fd", bias_correction="shuffle"`
165
+ reproduces the old scores. See the
166
+ [changelog](https://github.com/calebdame/pymutualinfo/blob/main/CHANGELOG.md).
167
+
168
+ ## License
169
+
170
+ BSD 3-Clause. See [LICENSE](https://github.com/calebdame/pymutualinfo/blob/main/LICENSE).
@@ -0,0 +1,132 @@
1
+ # pymutualinfo
2
+
3
+ [![License: BSD-3-Clause](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](https://github.com/calebdame/pymutualinfo/blob/main/LICENSE)
4
+
5
+ Fast, accurate mutual information for ranking and selecting features in tabular data,
6
+ with redundancy-aware selectors (mRMR, CMIM, JMI) and native support for NaN and
7
+ string columns.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install pymutualinfo
13
+ ```
14
+
15
+ The package imports as `fastmi`:
16
+
17
+ ```python
18
+ import fastmi
19
+ ```
20
+
21
+ Requires Python 3.10 or newer. Dependencies: NumPy, pandas, scikit-learn, joblib and
22
+ tqdm.
23
+
24
+ ## Quick start
25
+
26
+ ```python
27
+ from fastmi import select_features_by_mutual_information, select_features_by_mrmr
28
+
29
+ scores = select_features_by_mutual_information(X, y, target_type="binary") # MI per column, in nats
30
+ order = select_features_by_mrmr(X, y, target_type="binary") # column indices, best first
31
+ ```
32
+
33
+ `X` is a pandas DataFrame or a 2-D NumPy array and `y` the target. Use
34
+ `target_type="classification"` for multiclass labels and `"continuous"` for regression
35
+ targets.
36
+
37
+ ## Why pymutualinfo
38
+
39
+ **Better rankings than scikit-learn's KSG estimator.** On 800 synthetic datasets with
40
+ exact ground-truth MI (heavy tails, skew, point masses, integer columns, weak and strong
41
+ signals), the default estimator orders features much closer to the true order:
42
+
43
+ | Estimator | Spearman with true MI order | Precision@k |
44
+ |---|---|---|
45
+ | **fastmi (default)** | **0.85** | **0.90** |
46
+ | scikit-learn KSG (`mutual_info_classif` / `mutual_info_regression`) | 0.67 | 0.74 |
47
+ | scikit-learn KSG on rank-transformed columns | 0.68 | 0.75 |
48
+ | fastmi 0.1 (Freedman-Diaconis bins) | 0.58 | 0.69 |
49
+
50
+ **Much faster.** Single process unless noted:
51
+
52
+ | Case | Speed-up over scikit-learn |
53
+ |---|---|
54
+ | Continuous features, n = 1e3 to 1e6 | 9-31x |
55
+ | Default scoring, p = 50, n = 2e4 | about 50x (0.04 s vs 2.15 s) |
56
+ | n = 1e6, p = 100, 8 processes on both sides | 18x (1.9 s vs 35 s) |
57
+ | Continuous target, low-cardinality integer features | 45-55x |
58
+ | Continuous target, high-cardinality (ID-like) integer features, n = 1e4 | about 900x (0.006 s vs 5.5 s) |
59
+
60
+ **Takes real-world data as is.** NaN forms its own category, string and categorical
61
+ columns are encoded for you (`encoding="label"` or `"frequency"`), and integer columns
62
+ are treated as categories or as ordinal values, whichever carries more information.
63
+ scikit-learn's estimators accept neither NaN nor strings.
64
+
65
+ **Selects features, not just scores them.** mRMR, CMIM and JMI penalise redundancy, so
66
+ near-duplicate columns do not crowd out independent signals.
67
+ `pairwise_interaction_information` screens for pairs, such as XOR, that are informative
68
+ only together.
69
+
70
+ The full results and the commands that reproduce them are in
71
+ [benchmarks/RESULTS.md](https://github.com/calebdame/pymutualinfo/blob/main/benchmarks/RESULTS.md)
72
+ (speed and selection against scikit-learn) and
73
+ [research/BINNING.md](https://github.com/calebdame/pymutualinfo/blob/main/research/BINNING.md)
74
+ (estimator study: ranking quality, absolute error, speed).
75
+
76
+ ## scikit-learn pipelines
77
+
78
+ `FastMISelector`, `MRMRSelector`, `CMIMSelector` and `JMISelector` are scikit-learn
79
+ transformers:
80
+
81
+ ```python
82
+ from sklearn.linear_model import LogisticRegression
83
+ from sklearn.pipeline import Pipeline
84
+ from fastmi import CMIMSelector
85
+
86
+ pipe = Pipeline([
87
+ ("select", CMIMSelector(k_features=20, target_type="binary")),
88
+ ("model", LogisticRegression()),
89
+ ])
90
+ pipe.fit(X, y)
91
+ ```
92
+
93
+ They support `get_feature_names_out` and `set_output(transform="pandas")`.
94
+
95
+ ## Choosing settings
96
+
97
+ The defaults are tuned for ranking and selecting features. For accurate absolute MI
98
+ values at n >= 5000, use `n_bins="accurate"`. For small samples with very strong
99
+ dependence, a kNN estimator on ranks is more accurate. The
100
+ [settings-by-goal table](https://github.com/calebdame/pymutualinfo/blob/main/docs/mutual_information.md#which-settings-for-which-goal)
101
+ covers these cases and the binning, bias-correction and integer-column options.
102
+
103
+ ## Documentation
104
+
105
+ - [Mutual information](https://github.com/calebdame/pymutualinfo/blob/main/docs/mutual_information.md):
106
+ `select_features_by_mutual_information`, `pairwise_mutual_information`,
107
+ `select_features_by_mrmr` and the estimator options.
108
+ - [Feature selection](https://github.com/calebdame/pymutualinfo/blob/main/docs/feature_selection.md):
109
+ CMIM, JMI, interaction information and the scikit-learn selectors.
110
+ - [Encoding](https://github.com/calebdame/pymutualinfo/blob/main/docs/encoding.md) and
111
+ [utilities](https://github.com/calebdame/pymutualinfo/blob/main/docs/utils.md).
112
+ - [Changelog](https://github.com/calebdame/pymutualinfo/blob/main/CHANGELOG.md).
113
+
114
+ ## Leak-free modeling
115
+
116
+ Selecting features on the full dataset and then evaluating on the same rows overstates
117
+ performance. The companion package
118
+ [outofsample](https://github.com/calebdame/outofsample) (`pip install outofsample`)
119
+ wraps scikit-learn estimators and pipelines, including a fastmi selector step, so that
120
+ every row is predicted by a model that never saw it.
121
+
122
+ ## Migrating from `fast_mi`
123
+
124
+ The package was called `fast_mi` before 0.2.0. `import fast_mi` still works but emits a
125
+ `DeprecationWarning`; replace it with `import fastmi`. Version 0.2.0 also changes the
126
+ default estimator, so scores differ from 0.1.0; `binning="fd", bias_correction="shuffle"`
127
+ reproduces the old scores. See the
128
+ [changelog](https://github.com/calebdame/pymutualinfo/blob/main/CHANGELOG.md).
129
+
130
+ ## License
131
+
132
+ BSD 3-Clause. See [LICENSE](https://github.com/calebdame/pymutualinfo/blob/main/LICENSE).
@@ -0,0 +1,41 @@
1
+ # Encoding Utilities
2
+
3
+ The `fastmi.encoding` module provides helpers for transforming categorical features into a numeric representation. These encodings are primarily used as a preprocessing step before computing mutual information scores.
4
+
5
+ ## `encode_features`
6
+
7
+ ```python
8
+ encode_features(features: pd.DataFrame | np.ndarray, method: str = "label") -> Tuple[np.ndarray, Dict[str, LabelEncoder | Dict[str, float]]]
9
+ ```
10
+
11
+ Encodes all non-numeric columns in `features` using one of two strategies:
12
+
13
+ * `label` – uses scikit‑learn's `LabelEncoder` to convert each unique category to an integer value.
14
+ * `frequency` – replaces each category with its frequency in the column.
15
+
16
+ ### Parameters
17
+
18
+ | Name | Type | Description |
19
+ |------|------|-------------|
20
+ | `features` | `pandas.DataFrame` or `numpy.ndarray` | The input feature matrix. Any non-numeric columns will be encoded. |
21
+ | `method` | `"label"` or `"frequency"` | Selects the encoding strategy. Defaults to `"label"`. |
22
+
23
+ ### Returns
24
+
25
+ A tuple containing the encoded feature matrix and a mapping of column names to their corresponding encoders. When `method="frequency"`, the mapping contains dictionaries from category value to frequency. For `label` encoding, scikit‑learn `LabelEncoder` instances are returned.
26
+
27
+ ### Example
28
+
29
+ ```python
30
+ import pandas as pd
31
+ from fastmi.encoding import encode_features
32
+
33
+ raw = pd.DataFrame({
34
+ "color": ["red", "blue", "red"],
35
+ "size": ["S", "M", "L"],
36
+ })
37
+ encoded, encoders = encode_features(raw, method="label")
38
+ ```
39
+
40
+ After running the above code, `encoded` is a NumPy array containing numeric values for the categorical columns and `encoders` holds the mapping objects used to perform the transformation.
41
+