diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..08c9ece --- /dev/null +++ b/.gitignore @@ -0,0 +1,113 @@ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +downloads/ +#eggs/ +#.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +#*.egg-info/ +.installed.cfg +#*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# IDE settings +.vscode/ +.Rproj.user +site/ + +# Apple files +.DS_Store + +# R files +*.Rhistory + +# Others +unifiedbooster-docs/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f9ba56f --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright <2024> + +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. \ No newline at end of file diff --git a/README.md b/README.md index 1358972..0c4819c 100644 --- a/README.md +++ b/README.md @@ -1 +1,91 @@ # unifiedbooster + +![PyPI](https://img.shields.io/pypi/v/unifiedbooster) [![PyPI - License](https://img.shields.io/pypi/l/unifiedbooster)](https://github.com/thierrymoudiki/unifiedbooster/blob/master/LICENSE) [![Downloads](https://pepy.tech/badge/unifiedbooster)](https://pepy.tech/project/unifiedbooster) +[![Documentation](https://img.shields.io/badge/documentation-is_here-green)](https://techtonique.github.io/unifiedbooster/) + +## Examples + +### classification + +```python +import unifiedbooster as ub +from sklearn.datasets import load_iris, load_breast_cancer, load_wine +from sklearn.model_selection import train_test_split +from sklearn.metrics import accuracy_score + +datasets = [load_iris(), load_breast_cancer(), load_wine()] + +for dataset in datasets: + + X, y = dataset.data, dataset.target + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + + # Initialize the unified regressor (example with XGBoost) + regressor1 = ub.GBDTClassifier(model_type='xgboost') + regressor2 = ub.GBDTClassifier(model_type='catboost') + regressor3 = ub.GBDTClassifier(model_type='lightgbm') + + # Fit the model + regressor1.fit(X_train, y_train) + regressor2.fit(X_train, y_train) + regressor3.fit(X_train, y_train) + + # Predict on the test set + y_pred1 = regressor1.predict(X_test) + y_pred2 = regressor2.predict(X_test) + y_pred3 = regressor3.predict(X_test) + + # Evaluate the model + accuracy1 = accuracy_score(y_test, y_pred1) + accuracy2 = accuracy_score(y_test, y_pred2) + accuracy3 = accuracy_score(y_test, y_pred3) + print("-------------------------") + print(f"Classification Accuracy xgboost: {accuracy1:.2f}") + print(f"Classification Accuracy catboost: {accuracy2:.2f}") + print(f"Classification Accuracy lightgbm: {accuracy3:.2f}") +``` + +### regression + +```python +import numpy as np +import unifiedbooster as ub +from sklearn.datasets import fetch_california_housing, load_diabetes +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error + + +datasets = [fetch_california_housing(), load_diabetes()] + +for dataset in datasets: + + # Load dataset + X, y = dataset.data, dataset.target + + # Split dataset into training and testing sets + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + + # Initialize the unified regressor (example with XGBoost) + regressor1 = ub.GBDTRegressor(model_type='xgboost') + regressor2 = ub.GBDTRegressor(model_type='catboost') + regressor3 = ub.GBDTRegressor(model_type='lightgbm') + + # Fit the model + regressor1.fit(X_train, y_train) + regressor2.fit(X_train, y_train) + regressor3.fit(X_train, y_train) + + # Predict on the test set + y_pred1 = regressor1.predict(X_test) + y_pred2 = regressor2.predict(X_test) + y_pred3 = regressor3.predict(X_test) + + # Evaluate the model + mse1 = np.sqrt(mean_squared_error(y_test, y_pred1)) + mse2 = np.sqrt(mean_squared_error(y_test, y_pred2)) + mse3 = np.sqrt(mean_squared_error(y_test, y_pred3)) + print("-------------------------") + print(f"Regression Root Mean Squared Error xgboost: {mse1:.2f}") + print(f"Regression Root Mean Squared Error catboost: {mse2:.2f}") + print(f"Regression Root Mean Squared Error lightgbm: {mse3:.2f}") +``` \ No newline at end of file diff --git a/examples/classification.py b/examples/classification.py index f0dd043..c57e161 100644 --- a/examples/classification.py +++ b/examples/classification.py @@ -1,6 +1,6 @@ import unifiedbooster as ub from sklearn.datasets import load_iris -from sklearn.model_selection import train_test_split +from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import accuracy_score # Load dataset @@ -10,20 +10,20 @@ # Split dataset into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) -# Initialize the unified regressor (example with XGBoost) -regressor1 = ub.GBDTClassifier(model_type='xgboost') -#regressor2 = ub.GBDTClassifier(model_type='catboost') -regressor3 = ub.GBDTClassifier(model_type='lightgbm') +# Initialize the unified clf (example with XGBoost) +clf1 = ub.GBDTClassifier(model_type='xgboost') +#clf2 = ub.GBDTClassifier(model_type='catboost') +clf3 = ub.GBDTClassifier(model_type='lightgbm') # Fit the model -regressor1.fit(X_train, y_train) -#regressor2.fit(X_train, y_train) -regressor3.fit(X_train, y_train) +clf1.fit(X_train, y_train) +#clf2.fit(X_train, y_train) +clf3.fit(X_train, y_train) # Predict on the test set -y_pred1 = regressor1.predict(X_test) -#y_pred2 = regressor2.predict(X_test) -y_pred3 = regressor3.predict(X_test) +y_pred1 = clf1.predict(X_test) +#y_pred2 = clf2.predict(X_test) +y_pred3 = clf3.predict(X_test) # Evaluate the model accuracy1 = accuracy_score(y_test, y_pred1) @@ -31,4 +31,6 @@ accuracy3 = accuracy_score(y_test, y_pred3) print(f"Classification Accuracy xgboost: {accuracy1:.2f}") #print(f"Classification Accuracy catboost: {accuracy2:.2f}") -print(f"Classification Accuracy lightgbm: {accuracy3:.2f}") \ No newline at end of file +print(f"Classification Accuracy lightgbm: {accuracy3:.2f}") +print(f"CV xgboost: {cross_val_score(clf1, X_train, y_train)}") +print(f"CV lightgbm: {cross_val_score(clf3, X_train, y_train)}") \ No newline at end of file diff --git a/examples/regression.py b/examples/regression.py index 07c4835..28fbb11 100644 --- a/examples/regression.py +++ b/examples/regression.py @@ -1,6 +1,6 @@ import unifiedbooster as ub from sklearn.datasets import fetch_california_housing -from sklearn.model_selection import train_test_split +from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import mean_squared_error # Load dataset @@ -10,20 +10,20 @@ # Split dataset into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) -# Initialize the unified regressor (example with XGBoost) -regressor1 = ub.GBDTRegressor(model_type='xgboost') -#regressor2 = ub.GBDTRegressor(model_type='catboost') -regressor3 = ub.GBDTRegressor(model_type='lightgbm') +# Initialize the unified regr (example with XGBoost) +regr1 = ub.GBDTregr(model_type='xgboost') +#regr2 = ub.GBDTregr(model_type='catboost') +regr3 = ub.GBDTregr(model_type='lightgbm') # Fit the model -regressor1.fit(X_train, y_train) -#regressor2.fit(X_train, y_train) -regressor3.fit(X_train, y_train) +regr1.fit(X_train, y_train) +#regr2.fit(X_train, y_train) +regr3.fit(X_train, y_train) # Predict on the test set -y_pred1 = regressor1.predict(X_test) -#y_pred2 = regressor2.predict(X_test) -y_pred3 = regressor3.predict(X_test) +y_pred1 = regr1.predict(X_test) +#y_pred2 = regr2.predict(X_test) +y_pred3 = regr3.predict(X_test) # Evaluate the model mse1 = mean_squared_error(y_test, y_pred1) @@ -32,3 +32,5 @@ print(f"Regression Mean Squared Error xgboost: {mse1:.2f}") #print(f"Regression Mean Squared Error catboost: {mse2:.2f}") print(f"Regression Mean Squared Error lightgbm: {mse3:.2f}") +print(f"CV xgboost: {cross_val_score(regr1, X_train, y_train)}") +print(f"CV lightgbm: {cross_val_score(regr3, X_train, y_train)}") \ No newline at end of file diff --git a/setup.py b/setup.py index 58559f9..8a699f7 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ subprocess.check_call(['pip', 'install', 'Cython']) -__version__ = "0.2.1" +__version__ = "0.2.2" here = path.abspath(path.dirname(__file__)) diff --git a/unifiedbooster/__init__.py b/unifiedbooster/__init__.py index b8164f0..4e1106b 100644 --- a/unifiedbooster/__init__.py +++ b/unifiedbooster/__init__.py @@ -1,4 +1,5 @@ +from .gbdt import GBDT from .gbdt_classification import GBDTClassifier from .gbdt_regression import GBDTRegressor -__all__ = ["GBDTClassifier", "GBDTRegressor"] \ No newline at end of file +__all__ = ["GBDT", "GBDTClassifier", "GBDTRegressor"] diff --git a/unifiedbooster/gbdt.py b/unifiedbooster/gbdt.py index c2c7d0e..f958dc0 100644 --- a/unifiedbooster/gbdt.py +++ b/unifiedbooster/gbdt.py @@ -1,69 +1,131 @@ -import numpy as np +import numpy as np from sklearn.base import BaseEstimator class GBDT(BaseEstimator): - def __init__(self, - model_type='xgboost', - n_estimators=100, - learning_rate=0.1, - max_depth=3, - rowsample=1.0, - colsample=1.0, - verbose=0, - seed=123, - **kwargs): - + """Gradient Boosted Decision Trees (GBDT) base class + + Attributes: + + n_estimators: int + maximum number of trees that can be built + + learning_rate: float + shrinkage rate; used for reducing the gradient step + + rowsample: float + subsample ratio of the training instances + + colsample: float + percentage of features to use at each node split + + verbose: int + controls verbosity (default=0) + + seed: int + reproducibility seed + """ + + def __init__( + self, + model_type="xgboost", + n_estimators=100, + learning_rate=0.1, + max_depth=3, + rowsample=1.0, + colsample=1.0, + verbose=0, + seed=123, + **kwargs + ): + self.model_type = model_type self.n_estimators = n_estimators self.learning_rate = learning_rate self.max_depth = max_depth self.rowsample = rowsample - self.colsample = colsample - self.verbose = verbose - self.seed = seed + self.colsample = colsample + self.verbose = verbose + self.seed = seed - if self.model_type == "xgboost": + if self.model_type == "xgboost": self.params = { - 'n_estimators': self.n_estimators, - 'learning_rate': self.learning_rate, - 'subsample': self.rowsample, - 'colsample_bynode': self.colsample, - 'max_depth': self.max_depth, - 'verbosity': self.verbose, - 'seed': self.seed, - **kwargs + "n_estimators": self.n_estimators, + "learning_rate": self.learning_rate, + "subsample": self.rowsample, + "colsample_bynode": self.colsample, + "max_depth": self.max_depth, + "verbosity": self.verbose, + "seed": self.seed, + **kwargs, } elif self.model_type == "lightgbm": - verbose = self.verbose - 1 if self.verbose==0 else self.verbose - self.params = { - 'n_estimators': self.n_estimators, - 'learning_rate': self.learning_rate, - 'subsample': self.rowsample, - 'feature_fraction_bynode': self.colsample, - 'max_depth': self.max_depth, - 'verbose': verbose, # keep this way - 'seed': self.seed, - **kwargs + verbose = self.verbose - 1 if self.verbose == 0 else self.verbose + self.params = { + "n_estimators": self.n_estimators, + "learning_rate": self.learning_rate, + "subsample": self.rowsample, + "feature_fraction_bynode": self.colsample, + "max_depth": self.max_depth, + "verbose": verbose, # keep this way + "seed": self.seed, + **kwargs, } elif self.model_type == "catboost": - self.params = { - 'iterations': self.n_estimators, - 'learning_rate': self.learning_rate, - 'subsample': self.rowsample, - 'rsm': self.colsample, - 'depth': self.max_depth, - 'verbose': self.verbose, - 'random_seed': self.seed, - 'bootstrap_type': 'Bernoulli', - **kwargs - } - + self.params = { + "iterations": self.n_estimators, + "learning_rate": self.learning_rate, + "subsample": self.rowsample, + "rsm": self.colsample, + "depth": self.max_depth, + "verbose": self.verbose, + "random_seed": self.seed, + "bootstrap_type": "Bernoulli", + **kwargs, + } + def fit(self, X, y, **kwargs): + """Fit custom model to training data (X, y). + + Parameters: + + X: {array-like}, shape = [n_samples, n_features] + Training vectors, where n_samples is the number + of samples and n_features is the number of features. + + y: array-like, shape = [n_samples] + Target values. + + **kwargs: additional parameters to be passed to + self.cook_training_set or self.obj.fit + + Returns: + + self: object + """ + if getattr(self, "type_fit") == "classification": - self.classes_ = np.unique(y) # for compatibility with sklearn - self.n_classes_ = len(self.classes_) # for compatibility with sklearn + self.classes_ = np.unique(y) # for compatibility with sklearn + self.n_classes_ = len( + self.classes_ + ) # for compatibility with sklearn return getattr(self, "model").fit(X, y, **kwargs) - + def predict(self, X): - return getattr(self, "model").predict(X) \ No newline at end of file + """Predict test data X. + + Parameters: + + X: {array-like}, shape = [n_samples, n_features] + Training vectors, where n_samples is the number + of samples and n_features is the number of features. + + **kwargs: additional parameters to be passed to + self.cook_test_set + + Returns: + + model predictions: {array-like} + """ + + return getattr(self, "model").predict(X) diff --git a/unifiedbooster/gbdt_classification.py b/unifiedbooster/gbdt_classification.py index 74ba45d..f4c693d 100644 --- a/unifiedbooster/gbdt_classification.py +++ b/unifiedbooster/gbdt_classification.py @@ -1,7 +1,11 @@ from .gbdt import GBDT from sklearn.base import ClassifierMixin from xgboost import XGBClassifier -from catboost import CatBoostClassifier + +try: + from catboost import CatBoostClassifier +except: + print("catboost package can't be built") from lightgbm import LGBMClassifier @@ -11,7 +15,7 @@ class GBDTClassifier(GBDT, ClassifierMixin): Attributes: n_estimators: int - maximum number of trees that can be built + maximum number of trees that can be built learning_rate: float shrinkage rate; used for reducing the gradient step @@ -24,9 +28,9 @@ class GBDTClassifier(GBDT, ClassifierMixin): verbose: int controls verbosity (default=0) - - seed: int - reproducibility seed + + seed: int + reproducibility seed Examples: @@ -68,39 +72,57 @@ class GBDTClassifier(GBDT, ClassifierMixin): ``` """ - def __init__(self, - model_type='xgboost', - n_estimators=100, - learning_rate=0.1, - max_depth=3, - rowsample=1.0, - colsample=1.0, - verbose=0, - seed=123, - **kwargs): - + def __init__( + self, + model_type="xgboost", + n_estimators=100, + learning_rate=0.1, + max_depth=3, + rowsample=1.0, + colsample=1.0, + verbose=0, + seed=123, + **kwargs, + ): + self.type_fit = "classification" - + super().__init__( - model_type=model_type, - n_estimators=n_estimators, - learning_rate=learning_rate, - max_depth=max_depth, + model_type=model_type, + n_estimators=n_estimators, + learning_rate=learning_rate, + max_depth=max_depth, rowsample=rowsample, - colsample=colsample, - verbose=verbose, - seed=seed, - **kwargs + colsample=colsample, + verbose=verbose, + seed=seed, + **kwargs, ) - if model_type == 'xgboost': + if model_type == "xgboost": self.model = XGBClassifier(**self.params) - elif model_type == 'catboost': + elif model_type == "catboost": self.model = CatBoostClassifier(**self.params) - elif model_type == 'lightgbm': + elif model_type == "lightgbm": self.model = LGBMClassifier(**self.params) else: raise ValueError(f"Unknown model_type: {model_type}") - + def predict_proba(self, X): - return self.model.predict_proba(X) \ No newline at end of file + """Predict probabilities for test data X. + + Args: + + X: {array-like}, shape = [n_samples, n_features] + Training vectors, where n_samples is the number + of samples and n_features is the number of features. + + **kwargs: additional parameters to be passed to + self.cook_test_set + + Returns: + + probability estimates for test data: {array-like} + """ + + return self.model.predict_proba(X) diff --git a/unifiedbooster/gbdt_regression.py b/unifiedbooster/gbdt_regression.py index 5b52a54..18e19f7 100644 --- a/unifiedbooster/gbdt_regression.py +++ b/unifiedbooster/gbdt_regression.py @@ -1,7 +1,11 @@ from .gbdt import GBDT from sklearn.base import RegressorMixin from xgboost import XGBRegressor -from catboost import CatBoostRegressor + +try: + from catboost import CatBoostRegressor +except: + print("catboost package can't be built") from lightgbm import LGBMRegressor @@ -11,7 +15,7 @@ class GBDTRegressor(GBDT, RegressorMixin): Attributes: n_estimators: int - maximum number of trees that can be built + maximum number of trees that can be built learning_rate: float shrinkage rate; used for reducing the gradient step @@ -24,9 +28,9 @@ class GBDTRegressor(GBDT, RegressorMixin): verbose: int controls verbosity (default=0) - - seed: int - reproducibility seed + + seed: int + reproducibility seed Examples: @@ -68,36 +72,38 @@ class GBDTRegressor(GBDT, RegressorMixin): ``` """ - def __init__(self, - model_type='xgboost', - n_estimators=100, - learning_rate=0.1, - max_depth=3, - rowsample=1.0, - colsample=1.0, - verbose=0, - seed=123, - **kwargs): - + def __init__( + self, + model_type="xgboost", + n_estimators=100, + learning_rate=0.1, + max_depth=3, + rowsample=1.0, + colsample=1.0, + verbose=0, + seed=123, + **kwargs, + ): + self.type_fit = "regression" - + super().__init__( - model_type=model_type, - n_estimators=n_estimators, - learning_rate=learning_rate, - max_depth=max_depth, + model_type=model_type, + n_estimators=n_estimators, + learning_rate=learning_rate, + max_depth=max_depth, rowsample=rowsample, - colsample=colsample, - verbose=verbose, - seed=seed, - **kwargs + colsample=colsample, + verbose=verbose, + seed=seed, + **kwargs, ) - if model_type == 'xgboost': + if model_type == "xgboost": self.model = XGBRegressor(**self.params) - elif model_type == 'catboost': + elif model_type == "catboost": self.model = CatBoostRegressor(**self.params) - elif model_type == 'lightgbm': + elif model_type == "lightgbm": self.model = LGBMRegressor(**self.params) else: raise ValueError(f"Unknown model_type: {model_type}")