empulse
Value-driven and cost-sensitive analysis for scikit-learn
Science Score: 67.0%
This score indicates how likely this project is to be science-related based on various indicators:
-
✓CITATION.cff file
Found CITATION.cff file -
✓codemeta.json file
Found codemeta.json file -
✓.zenodo.json file
Found .zenodo.json file -
✓DOI references
Found 1 DOI reference(s) in README -
✓Academic publication links
Links to: zenodo.org -
○Academic email domains
-
○Institutional organization owner
-
○JOSS paper metadata
-
○Scientific vocabulary similarity
Low similarity (17.3%) to scientific vocabulary
Keywords
Repository
Value-driven and cost-sensitive analysis for scikit-learn
Basic Info
- Host: GitHub
- Owner: ShimantoRahman
- License: other
- Language: Python
- Default Branch: main
- Homepage: https://empulse.readthedocs.io/en/stable/
- Size: 13.2 MB
Statistics
- Stars: 22
- Watchers: 1
- Forks: 1
- Open Issues: 0
- Releases: 10
Topics
Metadata Files
README.md
Empulse
Empulse is a package aimed to enable value-driven and cost-sensitive analysis in Python. The package implements popular value-driven and cost-sensitive metrics and algorithms in accordance to sci-kit learn conventions. This allows the measures to seamlessly integrate into existing ML workflows.
Installation
Empulse requires python 3.10 or higher.
Install empulse via pip with
bash
pip install empulse
Documentation
You can find the documentation here.
Features
- Ready to use out of the box with scikit-learn
- Use case specific profit and cost metrics
- Flexible profit-driven and cost-sensitive models
- Easy passing of instance-dependent costs
- Cost-aware resampling and relabeling
- Find the optimal decision threshold
- Easy access to real-world datasets for benchmarking
Take the tour
Ready to use out of the box with scikit-learn
All components of the package are designed to work seamlessly with scikit-learn.
Models are implemented as scikit-learn estimators and can be used anywhere a scikit-learn estimator can be used.
Pipelines
```python from empulse.models import CSLogitClassifier from sklearn.datasets import make_classification from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler
X, y = makeclassification() pipeline = Pipeline([ ("scaler", StandardScaler()), ("model", CSLogitClassifier()) ]) pipeline.fit(X, y, modelfpcost=2, model_fncost=1) ```
Cross-validation
```python from sklearn.modelselection import crossval_score
crossvalscore( pipeline, X, y, scoring="rocauc", params={"modelfpcost": 2, "model_fncost": 1} ) ```
Grid search
```python from sklearn.model_selection import GridSearchCV
paramgrid = {"modelC": [0.1, 1, 10]} gridsearch = GridSearchCV(pipeline, paramgrid, scoring="rocauc") gridsearch.fit(X, y, modelfpcost=2, model_fncost=1) ```
All metrics can easily be converted as scikit-learn scorers and can be used in the same way as any other scikit-learn scorer.
```python from empulse.metrics import expectedcostloss from sklearn.metrics import make_scorer
scorer = makescorer( expectedcostloss, responsemethod="predictproba", greaterisbetter=False, fpcost=2, fncost=1 ) crossval_score(pipeline, X, y, scoring=scorer) ```
Use case specific profit and cost metrics
Empulse offers a wide range of profit and cost metrics that are tailored to specific use cases such as: - customer churn, - customer acquisition, - credit scoring, - and fraud detection (coming soon).
For other use cases, the package provides a generic implementations for: - the Metric class to define your own custom metrics, - the cost loss, - the expected cost loss, - the expected log cost loss, - the savings score, - the expected savings score, - and the maximum profit score.
Flexible profit-driven and cost-sensitive models
Empulse provides a range of profit-driven and cost-sensitive models such as: - CSLogitClassifier, - CSBoostClassifier, - B2BoostClassifier, - RobustCSClassifier, - ProfLogitClassifier, - BiasRelabelingClassifier, - BiasResamplingClassifier, - and BiasReweighingClassifier.
Each classifier tries to balance ease of use through good defaults and flexibility through a wide range of parameters.
For instance, the CSLogitClassifier allows you to change the loss function and the optimization method:
```python import numpy as np from empulse.models import CSLogitClassifier from empulse.metrics import expectedsavingsscore from scipy.optimize import minimize, OptimizeResult
def optimize(objective, X, *kwargs) -> OptimizeResult: initialguess = np.zeros(X.shape[1]) result = minimize( lambda x: -objective(x), # inverse objective function to maximize initialguess, method='BFGS', *kwargs ) return result model = CSLogitClassifier(loss=expectedsavingsscore, optimize_fn=optimize) ```
Easy passing of instance-dependent costs
Instance-dependent costs can easily be passed to the models through metadata routing.
For instance, the instance-dependent costs are passed dynamically to each fold of the cross-validation
through requesting the costs in the set_fit_request method of the model
and the set_score_request method of the scorer.
```python import numpy as np from empulse.models import CSLogitClassifier from empulse.metrics import expectedcostloss from sklearn import setconfig from sklearn.datasets import makeclassification from sklearn.modelselection import crossvalscore from sklearn.metrics import makescorer from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler
setconfig(enablemetadata_routing=True)
X, y = makeclassification() fpcost = np.random.rand(y.size) fn_cost = np.random.rand(y.size)
pipeline = Pipeline([ ("scale", StandardScaler()), ("model", CSLogitClassifier().setfitrequest(fpcost=True, fncost=True)) ])
scorer = makescorer( expectedcostloss, responsemethod="predictproba", greaterisbetter=False, ).setscorerequest(fpcost=True, fn_cost=True)
crossvalscore(pipeline, X, y, scoring=scorer, params={"fpcost": fpcost, "fncost": fncost}) ```
Cost-aware resampling and relabeling
Empulse uses the imbalanced-learn package to provide cost-aware resampling and relabeling techniques: - CostSensitiveSampler - BiasResampler - BiasRelabler
```python from empulse.samplers import CostSensitiveSampler from sklearn.datasets import make_classification
X, y = makeclassification() sampler = CostSensitiveSampler() Xresampled, yresampled = sampler.fitresample(X, y, fpcost=2, fncost=1) ```
They can be used in an imbalanced-learn pipeline:
```python import numpy as np from empulse.samplers import CostSensitiveSampler from imblearn.pipeline import Pipeline from sklearn import setconfig from sklearn.datasets import makeclassification from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression
setconfig(enablemetadata_routing=True)
X, y = makeclassification() fpcost = np.random.rand(y.size) fncost = np.random.rand(y.size) pipeline = Pipeline([ ("scaler", StandardScaler()), ("sampler", CostSensitiveSampler().setfitresamplerequest(fpcost=True, fncost=True)), ("model", LogisticRegression()) ])
pipeline.fit(X, y, fpcost=fpcost, fncost=fncost) ```
Find the optimal decision threshold
Empulse provides the
CSThresholdClassifier
which allows you to find the optimal decision threshold for a given cost matrix to minimize the expected cost loss.
The meta-estimator changes the predict method of the base estimator to predict the class with the lowest expected cost.
```python from empulse.models import CSThresholdClassifier from sklearn.datasets import makeclassification from sklearn.linearmodel import LogisticRegression
X, y = makeclassification() model = CSThresholdClassifier(estimator=LogisticRegression()) model.fit(X, y) model.predict(X, fpcost=2, fn_cost=1) ```
Metrics like the maximum profit score conveniently return the optimal target threshold. For example the Expected Maximum Profit measure for customer churn (EMPC) tells you what fraction of the customer base should be targeted to maximize profit.
```python from empulse.metrics import empc from sklearn.datasets import makeclassification from sklearn.linearmodel import LogisticRegression
X, y = makeclassification() model = LogisticRegression() predictions = model.fit(X, y).predictproba(X)[:, 1]
score, threshold = empc(y, predictions, clv=50) ```
This score can then be converted to a decision threshold by using the
classification_threshold
function.
```python from empulse.metrics import classification_threshold
decisionthreshold = classificationthreshold(y, predictions, customer_threshold=threshold) ```
This can then be combined with sci-kit learn's
FixedThresholdClassifier
to create a model that predicts the class with the highest expected profit.
```python from sklearn.model_selection import FixedThresholdClassifier
model = FixedThresholdClassifier(estimator=model, threshold=decision_threshold) model.predict(X) ```
Easy access to real-world datasets for benchmarking
Empulse provides easy access to real-world datasets for benchmarking cost-sensitive models.
Each dataset returns the features, the target, and the instance-dependent costs, ready to use in a cost-sensitive model.
```python from empulse.datasets import loadgivemesomecredit from empulse.models import CSLogitClassifier from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler
X, y, tpcost, fpcost, tncost, fncost = loadgivemesomecredit(returnXy_costs=True)
pipeline = Pipeline([ ('scaler', StandardScaler()), ('model', CSLogitClassifier()) ]) pipeline.fit( X, y, modeltpcost=tpcost, modelfpcost=fpcost, modeltncost=tncost, modelfncost=fncost ) ```
Owner
- Name: Shimanto Rahman
- Login: ShimantoRahman
- Kind: user
- Repositories: 1
- Profile: https://github.com/ShimantoRahman
Citation (CITATION.cff)
cff-version: 1.2.0
message: "If you use this software, please cite it as below."
authors:
- family-names: Rahman
given-names: Shimanto
orcid: https://orcid.org/0000-0001-8636-8970
- family-names: Janssens
given-names: Bram
orcid: https://orcid.org/0000-0003-3078-7919
- family-names: Bogaert
given-names: Matthias
orcid: https://orcid.org/0000-0002-4502-0764
title: "Empulse"
version: 0.9.0
identifiers:
- type: doi
value: 10.5281/zenodo.11185664
date-released: 2024-05-13
url: "https://github.com/ShimantoRahman/empulse"
GitHub Events
Total
- Release event: 9
- Watch event: 19
- Delete event: 4
- Push event: 123
- Fork event: 1
- Create event: 14
Last Year
- Release event: 9
- Watch event: 19
- Delete event: 4
- Push event: 123
- Fork event: 1
- Create event: 14
Issues and Pull Requests
Last synced: 6 months ago
All Time
- Total issues: 0
- Total pull requests: 0
- Average time to close issues: N/A
- Average time to close pull requests: N/A
- Total issue authors: 0
- Total pull request authors: 0
- Average comments per issue: 0
- Average comments per pull request: 0
- Merged pull requests: 0
- Bot issues: 0
- Bot pull requests: 0
Past Year
- Issues: 0
- Pull requests: 0
- Average time to close issues: N/A
- Average time to close pull requests: N/A
- Issue authors: 0
- Pull request authors: 0
- Average comments per issue: 0
- Average comments per pull request: 0
- Merged pull requests: 0
- Bot issues: 0
- Bot pull requests: 0
Top Authors
Issue Authors
Pull Request Authors
Top Labels
Issue Labels
Pull Request Labels
Packages
- Total packages: 1
-
Total downloads:
- pypi 123 last-month
- Total dependent packages: 1
- Total dependent repositories: 0
- Total versions: 23
- Total maintainers: 1
pypi.org: empulse
Value-driven and cost-sensitive tools for scikit-learn
- Documentation: https://empulse.readthedocs.io/
- License: MIT License Copyright (c) 2023 Shimanto Rahman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. == Empulse contains code that is licensed by third-party developers. == SciPy The Empulse project contains the codes from SciPy project. Copyright (c) 2001-2002 Enthought, Inc. 2003-2022, SciPy Developers. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. == CostCla The Empulse project contains the codes from CostCla project. Copyright (c) 2014, Alejandro Correa Bahnsen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the {organization} nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
Latest release: 0.9.0
published 8 months ago
Rankings
Maintainers (1)
Dependencies
- actions/checkout v3 composite
- actions/setup-python v3 composite
- peaceiris/actions-gh-pages v3 composite
- numba >=0.57.0
- numpy >=1.24.2
- patsy >=0.5.3
- scikit_learn >=1.2.1
- scipy >=1.10.1
- setuptools >=67.3.2
- xgboost >=1.7.4
- numba >=0.57.0
- numpy >=1.24.2
- patsy >=0.5.3
- scikit_learn >=1.2.1
- scipy >=1.10.1
- xgboost >=1.7.4
