unifiedbooster 0.2.1__tar.gz → 0.3.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.
@@ -0,0 +1,7 @@
1
+ Copyright <2024> <T. Moudiki>
2
+
3
+ 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:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ 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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: unifiedbooster
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: Unified interface for Gradient Boosted Decision Trees
5
5
  Home-page: https://github.com/thierrymoudiki/unifiedbooster
6
6
  Author: T. Moudiki
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.6
16
16
  Classifier: Programming Language :: Python :: 3.7
17
17
  Classifier: Programming Language :: Python :: 3.8
18
18
  Requires-Python: >=3.6
19
+ License-File: LICENSE
19
20
  Requires-Dist: Cython
20
21
  Requires-Dist: numpy
21
22
  Requires-Dist: scikit-learn
@@ -0,0 +1,93 @@
1
+ # unifiedbooster
2
+
3
+ Unified interface for Gradient Boosted Decision Trees algorithms
4
+
5
+ ![PyPI](https://img.shields.io/pypi/v/unifiedbooster) [![PyPI - License](https://img.shields.io/pypi/l/unifiedbooster)](https://github.com/thierrymoudiki/unifiedbooster/blob/main/LICENSE) [![Downloads](https://pepy.tech/badge/unifiedbooster)](https://pepy.tech/project/unifiedbooster)
6
+ [![Documentation](https://img.shields.io/badge/documentation-is_here-green)](https://techtonique.github.io/unifiedbooster/)
7
+
8
+ ## Examples
9
+
10
+ ### classification
11
+
12
+ ```python
13
+ import unifiedbooster as ub
14
+ from sklearn.datasets import load_iris, load_breast_cancer, load_wine
15
+ from sklearn.model_selection import train_test_split
16
+ from sklearn.metrics import accuracy_score
17
+
18
+ datasets = [load_iris(), load_breast_cancer(), load_wine()]
19
+
20
+ for dataset in datasets:
21
+
22
+ X, y = dataset.data, dataset.target
23
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
24
+
25
+ # Initialize the unified regressor (example with XGBoost)
26
+ regressor1 = ub.GBDTClassifier(model_type='xgboost')
27
+ regressor2 = ub.GBDTClassifier(model_type='catboost')
28
+ regressor3 = ub.GBDTClassifier(model_type='lightgbm')
29
+
30
+ # Fit the model
31
+ regressor1.fit(X_train, y_train)
32
+ regressor2.fit(X_train, y_train)
33
+ regressor3.fit(X_train, y_train)
34
+
35
+ # Predict on the test set
36
+ y_pred1 = regressor1.predict(X_test)
37
+ y_pred2 = regressor2.predict(X_test)
38
+ y_pred3 = regressor3.predict(X_test)
39
+
40
+ # Evaluate the model
41
+ accuracy1 = accuracy_score(y_test, y_pred1)
42
+ accuracy2 = accuracy_score(y_test, y_pred2)
43
+ accuracy3 = accuracy_score(y_test, y_pred3)
44
+ print("-------------------------")
45
+ print(f"Classification Accuracy xgboost: {accuracy1:.2f}")
46
+ print(f"Classification Accuracy catboost: {accuracy2:.2f}")
47
+ print(f"Classification Accuracy lightgbm: {accuracy3:.2f}")
48
+ ```
49
+
50
+ ### regression
51
+
52
+ ```python
53
+ import numpy as np
54
+ import unifiedbooster as ub
55
+ from sklearn.datasets import fetch_california_housing, load_diabetes
56
+ from sklearn.model_selection import train_test_split
57
+ from sklearn.metrics import mean_squared_error
58
+
59
+
60
+ datasets = [fetch_california_housing(), load_diabetes()]
61
+
62
+ for dataset in datasets:
63
+
64
+ # Load dataset
65
+ X, y = dataset.data, dataset.target
66
+
67
+ # Split dataset into training and testing sets
68
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
69
+
70
+ # Initialize the unified regressor (example with XGBoost)
71
+ regressor1 = ub.GBDTRegressor(model_type='xgboost')
72
+ regressor2 = ub.GBDTRegressor(model_type='catboost')
73
+ regressor3 = ub.GBDTRegressor(model_type='lightgbm')
74
+
75
+ # Fit the model
76
+ regressor1.fit(X_train, y_train)
77
+ regressor2.fit(X_train, y_train)
78
+ regressor3.fit(X_train, y_train)
79
+
80
+ # Predict on the test set
81
+ y_pred1 = regressor1.predict(X_test)
82
+ y_pred2 = regressor2.predict(X_test)
83
+ y_pred3 = regressor3.predict(X_test)
84
+
85
+ # Evaluate the model
86
+ mse1 = np.sqrt(mean_squared_error(y_test, y_pred1))
87
+ mse2 = np.sqrt(mean_squared_error(y_test, y_pred2))
88
+ mse3 = np.sqrt(mean_squared_error(y_test, y_pred3))
89
+ print("-------------------------")
90
+ print(f"Regression Root Mean Squared Error xgboost: {mse1:.2f}")
91
+ print(f"Regression Root Mean Squared Error catboost: {mse2:.2f}")
92
+ print(f"Regression Root Mean Squared Error lightgbm: {mse3:.2f}")
93
+ ```
@@ -10,7 +10,7 @@ from os import path
10
10
 
11
11
  subprocess.check_call(['pip', 'install', 'Cython'])
12
12
 
13
- __version__ = "0.2.1"
13
+ __version__ = "0.3.0"
14
14
 
15
15
  here = path.abspath(path.dirname(__file__))
16
16
 
@@ -1,4 +1,5 @@
1
+ from .gbdt import GBDT
1
2
  from .gbdt_classification import GBDTClassifier
2
3
  from .gbdt_regression import GBDTRegressor
3
4
 
4
- __all__ = ["GBDTClassifier", "GBDTRegressor"]
5
+ __all__ = ["GBDT", "GBDTClassifier", "GBDTRegressor"]
@@ -0,0 +1,151 @@
1
+ import numpy as np
2
+ from sklearn.base import BaseEstimator
3
+
4
+
5
+ class GBDT(BaseEstimator):
6
+ """Gradient Boosted Decision Trees (GBDT) base class
7
+
8
+ Attributes:
9
+
10
+ model_type: str
11
+ type of gradient boosting algorithm: 'xgboost', 'lightgbm',
12
+ 'catboost', 'gradientboosting'
13
+
14
+ n_estimators: int
15
+ maximum number of trees that can be built
16
+
17
+ learning_rate: float
18
+ shrinkage rate; used for reducing the gradient step
19
+
20
+ rowsample: float
21
+ subsample ratio of the training instances
22
+
23
+ colsample: float
24
+ percentage of features to use at each node split
25
+
26
+ verbose: int
27
+ controls verbosity (default=0)
28
+
29
+ seed: int
30
+ reproducibility seed
31
+
32
+ **kwargs: dict
33
+ additional parameters to be passed to the class
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ model_type="xgboost",
39
+ n_estimators=100,
40
+ learning_rate=0.1,
41
+ max_depth=3,
42
+ rowsample=1.0,
43
+ colsample=1.0,
44
+ verbose=0,
45
+ seed=123,
46
+ **kwargs
47
+ ):
48
+
49
+ self.model_type = model_type
50
+ self.n_estimators = n_estimators
51
+ self.learning_rate = learning_rate
52
+ self.max_depth = max_depth
53
+ self.rowsample = rowsample
54
+ self.colsample = colsample
55
+ self.verbose = verbose
56
+ self.seed = seed
57
+
58
+ if self.model_type == "xgboost":
59
+ self.params = {
60
+ "n_estimators": self.n_estimators,
61
+ "learning_rate": self.learning_rate,
62
+ "subsample": self.rowsample,
63
+ "colsample_bynode": self.colsample,
64
+ "max_depth": self.max_depth,
65
+ "verbosity": self.verbose,
66
+ "seed": self.seed,
67
+ **kwargs,
68
+ }
69
+ elif self.model_type == "lightgbm":
70
+ verbose = self.verbose - 1 if self.verbose == 0 else self.verbose
71
+ self.params = {
72
+ "n_estimators": self.n_estimators,
73
+ "learning_rate": self.learning_rate,
74
+ "subsample": self.rowsample,
75
+ "feature_fraction_bynode": self.colsample,
76
+ "max_depth": self.max_depth,
77
+ "verbose": verbose, # keep this way
78
+ "seed": self.seed,
79
+ **kwargs,
80
+ }
81
+ elif self.model_type == "catboost":
82
+ self.params = {
83
+ "iterations": self.n_estimators,
84
+ "learning_rate": self.learning_rate,
85
+ "subsample": self.rowsample,
86
+ "rsm": self.colsample,
87
+ "depth": self.max_depth,
88
+ "verbose": self.verbose,
89
+ "random_seed": self.seed,
90
+ "bootstrap_type": "Bernoulli",
91
+ **kwargs,
92
+ }
93
+ elif self.model_type == "gradientboosting":
94
+ self.params = {
95
+ "n_estimators": self.n_estimators,
96
+ "learning_rate": self.learning_rate,
97
+ "subsample": self.rowsample,
98
+ "max_features": self.colsample,
99
+ "max_depth": self.max_depth,
100
+ "verbose": self.verbose,
101
+ "random_state": self.seed,
102
+ **kwargs,
103
+ }
104
+
105
+ def fit(self, X, y, **kwargs):
106
+ """Fit custom model to training data (X, y).
107
+
108
+ Parameters:
109
+
110
+ X: {array-like}, shape = [n_samples, n_features]
111
+ Training vectors, where n_samples is the number
112
+ of samples and n_features is the number of features.
113
+
114
+ y: array-like, shape = [n_samples]
115
+ Target values.
116
+
117
+ **kwargs: additional parameters to be passed to
118
+ self.cook_training_set or self.obj.fit
119
+
120
+ Returns:
121
+
122
+ self: object
123
+ """
124
+
125
+ if getattr(self, "type_fit") == "classification":
126
+ self.classes_ = np.unique(y) # for compatibility with sklearn
127
+ self.n_classes_ = len(
128
+ self.classes_
129
+ ) # for compatibility with sklearn
130
+ if getattr(self, "model_type") == "gradientboosting":
131
+ self.model.max_features = int(self.model.max_features * X.shape[1])
132
+ return getattr(self, "model").fit(X, y, **kwargs)
133
+
134
+ def predict(self, X):
135
+ """Predict test data X.
136
+
137
+ Parameters:
138
+
139
+ X: {array-like}, shape = [n_samples, n_features]
140
+ Training vectors, where n_samples is the number
141
+ of samples and n_features is the number of features.
142
+
143
+ **kwargs: additional parameters to be passed to
144
+ self.cook_test_set
145
+
146
+ Returns:
147
+
148
+ model predictions: {array-like}
149
+ """
150
+
151
+ return getattr(self, "model").predict(X)
@@ -1,8 +1,13 @@
1
1
  from .gbdt import GBDT
2
2
  from sklearn.base import ClassifierMixin
3
3
  from xgboost import XGBClassifier
4
- from catboost import CatBoostClassifier
4
+
5
+ try:
6
+ from catboost import CatBoostClassifier
7
+ except:
8
+ print("catboost package can't be built")
5
9
  from lightgbm import LGBMClassifier
10
+ from sklearn.ensemble import GradientBoostingClassifier
6
11
 
7
12
 
8
13
  class GBDTClassifier(GBDT, ClassifierMixin):
@@ -10,8 +15,12 @@ class GBDTClassifier(GBDT, ClassifierMixin):
10
15
 
11
16
  Attributes:
12
17
 
18
+ model_type: str
19
+ type of gradient boosting algorithm: 'xgboost', 'lightgbm',
20
+ 'catboost', 'gradientboosting'
21
+
13
22
  n_estimators: int
14
- maximum number of trees that can be built
23
+ maximum number of trees that can be built
15
24
 
16
25
  learning_rate: float
17
26
  shrinkage rate; used for reducing the gradient step
@@ -24,9 +33,12 @@ class GBDTClassifier(GBDT, ClassifierMixin):
24
33
 
25
34
  verbose: int
26
35
  controls verbosity (default=0)
27
-
28
- seed: int
29
- reproducibility seed
36
+
37
+ seed: int
38
+ reproducibility seed
39
+
40
+ **kwargs: dict
41
+ additional parameters to be passed to the class
30
42
 
31
43
  Examples:
32
44
 
@@ -68,39 +80,59 @@ class GBDTClassifier(GBDT, ClassifierMixin):
68
80
  ```
69
81
  """
70
82
 
71
- def __init__(self,
72
- model_type='xgboost',
73
- n_estimators=100,
74
- learning_rate=0.1,
75
- max_depth=3,
76
- rowsample=1.0,
77
- colsample=1.0,
78
- verbose=0,
79
- seed=123,
80
- **kwargs):
81
-
83
+ def __init__(
84
+ self,
85
+ model_type="xgboost",
86
+ n_estimators=100,
87
+ learning_rate=0.1,
88
+ max_depth=3,
89
+ rowsample=1.0,
90
+ colsample=1.0,
91
+ verbose=0,
92
+ seed=123,
93
+ **kwargs,
94
+ ):
95
+
82
96
  self.type_fit = "classification"
83
-
97
+
84
98
  super().__init__(
85
- model_type=model_type,
86
- n_estimators=n_estimators,
87
- learning_rate=learning_rate,
88
- max_depth=max_depth,
99
+ model_type=model_type,
100
+ n_estimators=n_estimators,
101
+ learning_rate=learning_rate,
102
+ max_depth=max_depth,
89
103
  rowsample=rowsample,
90
- colsample=colsample,
91
- verbose=verbose,
92
- seed=seed,
93
- **kwargs
104
+ colsample=colsample,
105
+ verbose=verbose,
106
+ seed=seed,
107
+ **kwargs,
94
108
  )
95
109
 
96
- if model_type == 'xgboost':
110
+ if model_type == "xgboost":
97
111
  self.model = XGBClassifier(**self.params)
98
- elif model_type == 'catboost':
112
+ elif model_type == "catboost":
99
113
  self.model = CatBoostClassifier(**self.params)
100
- elif model_type == 'lightgbm':
114
+ elif model_type == "lightgbm":
101
115
  self.model = LGBMClassifier(**self.params)
116
+ elif model_type == "gradientboosting":
117
+ self.model = GradientBoostingClassifier(**self.params)
102
118
  else:
103
119
  raise ValueError(f"Unknown model_type: {model_type}")
104
-
120
+
105
121
  def predict_proba(self, X):
106
- return self.model.predict_proba(X)
122
+ """Predict probabilities for test data X.
123
+
124
+ Args:
125
+
126
+ X: {array-like}, shape = [n_samples, n_features]
127
+ Training vectors, where n_samples is the number
128
+ of samples and n_features is the number of features.
129
+
130
+ **kwargs: additional parameters to be passed to
131
+ self.cook_test_set
132
+
133
+ Returns:
134
+
135
+ probability estimates for test data: {array-like}
136
+ """
137
+
138
+ return self.model.predict_proba(X)
@@ -1,8 +1,13 @@
1
1
  from .gbdt import GBDT
2
2
  from sklearn.base import RegressorMixin
3
3
  from xgboost import XGBRegressor
4
- from catboost import CatBoostRegressor
4
+
5
+ try:
6
+ from catboost import CatBoostRegressor
7
+ except:
8
+ print("catboost package can't be built")
5
9
  from lightgbm import LGBMRegressor
10
+ from sklearn.ensemble import GradientBoostingRegressor
6
11
 
7
12
 
8
13
  class GBDTRegressor(GBDT, RegressorMixin):
@@ -10,8 +15,12 @@ class GBDTRegressor(GBDT, RegressorMixin):
10
15
 
11
16
  Attributes:
12
17
 
18
+ model_type: str
19
+ type of gradient boosting algorithm: 'xgboost', 'lightgbm',
20
+ 'catboost', 'gradientboosting'
21
+
13
22
  n_estimators: int
14
- maximum number of trees that can be built
23
+ maximum number of trees that can be built
15
24
 
16
25
  learning_rate: float
17
26
  shrinkage rate; used for reducing the gradient step
@@ -24,9 +33,12 @@ class GBDTRegressor(GBDT, RegressorMixin):
24
33
 
25
34
  verbose: int
26
35
  controls verbosity (default=0)
27
-
28
- seed: int
29
- reproducibility seed
36
+
37
+ seed: int
38
+ reproducibility seed
39
+
40
+ **kwargs: dict
41
+ additional parameters to be passed to the class
30
42
 
31
43
  Examples:
32
44
 
@@ -68,36 +80,40 @@ class GBDTRegressor(GBDT, RegressorMixin):
68
80
  ```
69
81
  """
70
82
 
71
- def __init__(self,
72
- model_type='xgboost',
73
- n_estimators=100,
74
- learning_rate=0.1,
75
- max_depth=3,
76
- rowsample=1.0,
77
- colsample=1.0,
78
- verbose=0,
79
- seed=123,
80
- **kwargs):
81
-
83
+ def __init__(
84
+ self,
85
+ model_type="xgboost",
86
+ n_estimators=100,
87
+ learning_rate=0.1,
88
+ max_depth=3,
89
+ rowsample=1.0,
90
+ colsample=1.0,
91
+ verbose=0,
92
+ seed=123,
93
+ **kwargs,
94
+ ):
95
+
82
96
  self.type_fit = "regression"
83
-
97
+
84
98
  super().__init__(
85
- model_type=model_type,
86
- n_estimators=n_estimators,
87
- learning_rate=learning_rate,
88
- max_depth=max_depth,
99
+ model_type=model_type,
100
+ n_estimators=n_estimators,
101
+ learning_rate=learning_rate,
102
+ max_depth=max_depth,
89
103
  rowsample=rowsample,
90
- colsample=colsample,
91
- verbose=verbose,
92
- seed=seed,
93
- **kwargs
104
+ colsample=colsample,
105
+ verbose=verbose,
106
+ seed=seed,
107
+ **kwargs,
94
108
  )
95
109
 
96
- if model_type == 'xgboost':
110
+ if model_type == "xgboost":
97
111
  self.model = XGBRegressor(**self.params)
98
- elif model_type == 'catboost':
112
+ elif model_type == "catboost":
99
113
  self.model = CatBoostRegressor(**self.params)
100
- elif model_type == 'lightgbm':
114
+ elif model_type == "lightgbm":
101
115
  self.model = LGBMRegressor(**self.params)
116
+ elif model_type == "gradientboosting":
117
+ self.model = GradientBoostingRegressor(**self.params)
102
118
  else:
103
119
  raise ValueError(f"Unknown model_type: {model_type}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: unifiedbooster
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: Unified interface for Gradient Boosted Decision Trees
5
5
  Home-page: https://github.com/thierrymoudiki/unifiedbooster
6
6
  Author: T. Moudiki
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.6
16
16
  Classifier: Programming Language :: Python :: 3.7
17
17
  Classifier: Programming Language :: Python :: 3.8
18
18
  Requires-Python: >=3.6
19
+ License-File: LICENSE
19
20
  Requires-Dist: Cython
20
21
  Requires-Dist: numpy
21
22
  Requires-Dist: scikit-learn
@@ -1,3 +1,4 @@
1
+ LICENSE
1
2
  README.md
2
3
  setup.py
3
4
  unifiedbooster/__init__.py
@@ -1 +0,0 @@
1
- # unifiedbooster
@@ -1,69 +0,0 @@
1
- import numpy as np
2
- from sklearn.base import BaseEstimator
3
-
4
-
5
- class GBDT(BaseEstimator):
6
- def __init__(self,
7
- model_type='xgboost',
8
- n_estimators=100,
9
- learning_rate=0.1,
10
- max_depth=3,
11
- rowsample=1.0,
12
- colsample=1.0,
13
- verbose=0,
14
- seed=123,
15
- **kwargs):
16
-
17
- self.model_type = model_type
18
- self.n_estimators = n_estimators
19
- self.learning_rate = learning_rate
20
- self.max_depth = max_depth
21
- self.rowsample = rowsample
22
- self.colsample = colsample
23
- self.verbose = verbose
24
- self.seed = seed
25
-
26
- if self.model_type == "xgboost":
27
- self.params = {
28
- 'n_estimators': self.n_estimators,
29
- 'learning_rate': self.learning_rate,
30
- 'subsample': self.rowsample,
31
- 'colsample_bynode': self.colsample,
32
- 'max_depth': self.max_depth,
33
- 'verbosity': self.verbose,
34
- 'seed': self.seed,
35
- **kwargs
36
- }
37
- elif self.model_type == "lightgbm":
38
- verbose = self.verbose - 1 if self.verbose==0 else self.verbose
39
- self.params = {
40
- 'n_estimators': self.n_estimators,
41
- 'learning_rate': self.learning_rate,
42
- 'subsample': self.rowsample,
43
- 'feature_fraction_bynode': self.colsample,
44
- 'max_depth': self.max_depth,
45
- 'verbose': verbose, # keep this way
46
- 'seed': self.seed,
47
- **kwargs
48
- }
49
- elif self.model_type == "catboost":
50
- self.params = {
51
- 'iterations': self.n_estimators,
52
- 'learning_rate': self.learning_rate,
53
- 'subsample': self.rowsample,
54
- 'rsm': self.colsample,
55
- 'depth': self.max_depth,
56
- 'verbose': self.verbose,
57
- 'random_seed': self.seed,
58
- 'bootstrap_type': 'Bernoulli',
59
- **kwargs
60
- }
61
-
62
- def fit(self, X, y, **kwargs):
63
- if getattr(self, "type_fit") == "classification":
64
- self.classes_ = np.unique(y) # for compatibility with sklearn
65
- self.n_classes_ = len(self.classes_) # for compatibility with sklearn
66
- return getattr(self, "model").fit(X, y, **kwargs)
67
-
68
- def predict(self, X):
69
- return getattr(self, "model").predict(X)
File without changes