mljar-supervised 1.2.1__py3-none-any.whl

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 (94) hide show
  1. mljar_supervised-1.2.1.dist-info/METADATA +657 -0
  2. mljar_supervised-1.2.1.dist-info/RECORD +94 -0
  3. mljar_supervised-1.2.1.dist-info/WHEEL +5 -0
  4. mljar_supervised-1.2.1.dist-info/licenses/LICENSE +21 -0
  5. mljar_supervised-1.2.1.dist-info/top_level.txt +1 -0
  6. supervised/__init__.py +14 -0
  7. supervised/algorithms/__init__.py +0 -0
  8. supervised/algorithms/algorithm.py +151 -0
  9. supervised/algorithms/baseline.py +90 -0
  10. supervised/algorithms/catboost.py +436 -0
  11. supervised/algorithms/decision_tree.py +305 -0
  12. supervised/algorithms/extra_trees.py +176 -0
  13. supervised/algorithms/factory.py +28 -0
  14. supervised/algorithms/knn.py +137 -0
  15. supervised/algorithms/lightgbm.py +406 -0
  16. supervised/algorithms/linear.py +211 -0
  17. supervised/algorithms/nn.py +180 -0
  18. supervised/algorithms/random_forest.py +181 -0
  19. supervised/algorithms/registry.py +76 -0
  20. supervised/algorithms/sklearn.py +197 -0
  21. supervised/algorithms/xgboost.py +413 -0
  22. supervised/automl.py +568 -0
  23. supervised/base_automl.py +2542 -0
  24. supervised/callbacks/__init__.py +0 -0
  25. supervised/callbacks/callback.py +25 -0
  26. supervised/callbacks/callback_list.py +33 -0
  27. supervised/callbacks/early_stopping.py +213 -0
  28. supervised/callbacks/learner_time_constraint.py +47 -0
  29. supervised/callbacks/max_iters_constraint.py +16 -0
  30. supervised/callbacks/metric_logger.py +48 -0
  31. supervised/callbacks/terminate_on_nan.py +28 -0
  32. supervised/callbacks/total_time_constraint.py +79 -0
  33. supervised/ensemble.py +583 -0
  34. supervised/exceptions.py +21 -0
  35. supervised/fairness/__init__.py +0 -0
  36. supervised/fairness/metrics.py +654 -0
  37. supervised/fairness/optimization.py +414 -0
  38. supervised/fairness/plots.py +131 -0
  39. supervised/fairness/report.py +116 -0
  40. supervised/fairness/utils.py +40 -0
  41. supervised/model_framework.py +734 -0
  42. supervised/preprocessing/__init__.py +0 -0
  43. supervised/preprocessing/datetime_transformer.py +106 -0
  44. supervised/preprocessing/encoding_selector.py +30 -0
  45. supervised/preprocessing/exclude_missing_target.py +46 -0
  46. supervised/preprocessing/goldenfeatures_transformer.py +310 -0
  47. supervised/preprocessing/kmeans_transformer.py +115 -0
  48. supervised/preprocessing/label_binarizer.py +81 -0
  49. supervised/preprocessing/label_encoder.py +54 -0
  50. supervised/preprocessing/preprocessing.py +652 -0
  51. supervised/preprocessing/preprocessing_categorical.py +117 -0
  52. supervised/preprocessing/preprocessing_missing.py +97 -0
  53. supervised/preprocessing/preprocessing_utils.py +136 -0
  54. supervised/preprocessing/scale.py +92 -0
  55. supervised/preprocessing/text_transformer.py +73 -0
  56. supervised/tuner/__init__.py +0 -0
  57. supervised/tuner/data_info.py +64 -0
  58. supervised/tuner/hill_climbing.py +80 -0
  59. supervised/tuner/mljar_tuner.py +1501 -0
  60. supervised/tuner/optuna/__init__.py +0 -0
  61. supervised/tuner/optuna/catboost.py +148 -0
  62. supervised/tuner/optuna/extra_trees.py +80 -0
  63. supervised/tuner/optuna/knn.py +64 -0
  64. supervised/tuner/optuna/lightgbm.py +165 -0
  65. supervised/tuner/optuna/nn.py +66 -0
  66. supervised/tuner/optuna/random_forest.py +77 -0
  67. supervised/tuner/optuna/tuner.py +335 -0
  68. supervised/tuner/optuna/xgboost.py +130 -0
  69. supervised/tuner/preprocessing_tuner.py +137 -0
  70. supervised/tuner/random_parameters.py +22 -0
  71. supervised/tuner/time_controller.py +273 -0
  72. supervised/utils/__init__.py +11 -0
  73. supervised/utils/additional_metrics.py +955 -0
  74. supervised/utils/additional_plots.py +228 -0
  75. supervised/utils/automl_plots.py +368 -0
  76. supervised/utils/common.py +39 -0
  77. supervised/utils/config.py +25 -0
  78. supervised/utils/constants.py +4 -0
  79. supervised/utils/data_validation.py +48 -0
  80. supervised/utils/importance.py +93 -0
  81. supervised/utils/jsonencoder.py +33 -0
  82. supervised/utils/leaderboard_plots.py +137 -0
  83. supervised/utils/learning_curves.py +145 -0
  84. supervised/utils/metric.py +450 -0
  85. supervised/utils/report_structured.py +525 -0
  86. supervised/utils/shap.py +373 -0
  87. supervised/utils/subsample.py +17 -0
  88. supervised/utils/utils.py +29 -0
  89. supervised/validation/__init__.py +0 -0
  90. supervised/validation/validation_step.py +37 -0
  91. supervised/validation/validator_base.py +17 -0
  92. supervised/validation/validator_custom.py +112 -0
  93. supervised/validation/validator_kfold.py +153 -0
  94. supervised/validation/validator_split.py +143 -0
@@ -0,0 +1,305 @@
1
+ import logging
2
+ import os
3
+ import warnings
4
+
5
+ import numpy as np
6
+ import sklearn
7
+ from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
8
+ from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
9
+
10
+ from supervised.algorithms.registry import (
11
+ BINARY_CLASSIFICATION,
12
+ MULTICLASS_CLASSIFICATION,
13
+ REGRESSION,
14
+ AlgorithmsRegistry,
15
+ )
16
+ from supervised.algorithms.sklearn import SklearnAlgorithm
17
+ from supervised.utils.config import LOG_LEVEL
18
+
19
+ logger = logging.getLogger(__name__)
20
+ logger.setLevel(LOG_LEVEL)
21
+
22
+ import dtreeviz
23
+ from sklearn.tree import _tree
24
+
25
+ from supervised.utils.subsample import subsample
26
+
27
+
28
+ def get_rules(tree, feature_names, class_names):
29
+ tree_ = tree.tree_
30
+ feature_name = [
31
+ feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
32
+ for i in tree_.feature
33
+ ]
34
+
35
+ paths = []
36
+ path = []
37
+
38
+ def recurse(node, path, paths):
39
+ if tree_.feature[node] != _tree.TREE_UNDEFINED:
40
+ name = feature_name[node]
41
+ threshold = tree_.threshold[node]
42
+ p1, p2 = list(path), list(path)
43
+ p1 += [f"({name} <= {np.round(threshold, 3)})"]
44
+ recurse(tree_.children_left[node], p1, paths)
45
+ p2 += [f"({name} > {np.round(threshold, 3)})"]
46
+ recurse(tree_.children_right[node], p2, paths)
47
+ else:
48
+ path += [(tree_.value[node], tree_.n_node_samples[node])]
49
+ paths += [path]
50
+
51
+ recurse(0, path, paths)
52
+
53
+ # sort by samples count
54
+ samples_count = [p[-1][1] for p in paths]
55
+ ii = list(np.argsort(samples_count))
56
+ paths = [paths[i] for i in reversed(ii)]
57
+
58
+ rules = []
59
+ for path in paths:
60
+ rule = "if "
61
+
62
+ for p in path[:-1]:
63
+ if rule != "if ":
64
+ rule += " and "
65
+ rule += str(p)
66
+ rule += " then "
67
+ if class_names is None:
68
+ rule += "response: " + str(np.round(path[-1][0][0][0], 3))
69
+ else:
70
+ classes = path[-1][0][0]
71
+ l = np.argmax(classes)
72
+ rule += f"class: {class_names[l]} (proba: {np.round(100.0*classes[l]/np.sum(classes),2)}%)"
73
+ rule += f" | based on {path[-1][1]:,} samples"
74
+ rules += [rule]
75
+
76
+ return rules
77
+
78
+
79
+ def save_rules(tree, feature_names, class_names, model_file_path, learner_name):
80
+ try:
81
+ rules = get_rules(tree, feature_names, class_names)
82
+ fname = os.path.join(model_file_path, f"{learner_name}_rules.txt")
83
+ with open(fname, "w") as fout:
84
+ for r in rules:
85
+ fout.write(r + "\n\n")
86
+ except Exception as e:
87
+ logger.info(f"Problem with extracting decision tree rules. {str(e)}")
88
+
89
+
90
+ class DecisionTreeAlgorithm(ClassifierMixin, SklearnAlgorithm):
91
+ algorithm_name = "Decision Tree"
92
+ algorithm_short_name = "Decision Tree"
93
+
94
+ def __init__(self, params):
95
+ super(DecisionTreeAlgorithm, self).__init__(params)
96
+ logger.debug("DecisionTreeAlgorithm.__init__")
97
+ self.library_version = sklearn.__version__
98
+ self.max_iters = additional.get("max_steps", 1)
99
+ self.model = DecisionTreeClassifier(
100
+ criterion=params.get("criterion", "gini"),
101
+ max_depth=params.get("max_depth", 3),
102
+ random_state=params.get("seed", 1),
103
+ )
104
+
105
+ def file_extension(self):
106
+ return "decision_tree"
107
+
108
+ def interpret(
109
+ self,
110
+ X_train,
111
+ y_train,
112
+ X_validation,
113
+ y_validation,
114
+ model_file_path,
115
+ learner_name,
116
+ target_name=None,
117
+ class_names=None,
118
+ metric_name=None,
119
+ ml_task=None,
120
+ explain_level=2,
121
+ ):
122
+ super(DecisionTreeAlgorithm, self).interpret(
123
+ X_train,
124
+ y_train,
125
+ X_validation,
126
+ y_validation,
127
+ model_file_path,
128
+ learner_name,
129
+ target_name,
130
+ class_names,
131
+ metric_name,
132
+ ml_task,
133
+ explain_level,
134
+ )
135
+ if explain_level == 0:
136
+ return
137
+ with warnings.catch_warnings():
138
+ warnings.simplefilter(action="ignore")
139
+ try:
140
+ if len(class_names) > 10:
141
+ # dtreeviz does not support more than 10 classes
142
+ return
143
+
144
+ viz = dtreeviz.model(
145
+ self.model,
146
+ X_train,
147
+ y_train,
148
+ target_name="target",
149
+ feature_names=X_train.columns,
150
+ class_names=class_names,
151
+ )
152
+ tree_file_plot = os.path.join(
153
+ model_file_path, learner_name + "_tree.svg"
154
+ )
155
+ viz.view().save(tree_file_plot)
156
+ except Exception as e:
157
+ logger.info(f"Problem when visualizing decision tree. {str(e)}")
158
+
159
+ save_rules(
160
+ self.model, X_train.columns, class_names, model_file_path, learner_name
161
+ )
162
+
163
+
164
+ class DecisionTreeRegressorAlgorithm(RegressorMixin, SklearnAlgorithm):
165
+ algorithm_name = "Decision Tree"
166
+ algorithm_short_name = "Decision Tree"
167
+
168
+ def __init__(self, params):
169
+ super(DecisionTreeRegressorAlgorithm, self).__init__(params)
170
+ logger.debug("DecisionTreeRegressorAlgorithm.__init__")
171
+ self.library_version = sklearn.__version__
172
+ self.max_iters = additional.get("max_steps", 1)
173
+ self.model = DecisionTreeRegressor(
174
+ criterion=params.get("criterion", "squared_error"),
175
+ max_depth=params.get("max_depth", 3),
176
+ random_state=params.get("seed", 1),
177
+ )
178
+
179
+ def file_extension(self):
180
+ return "decision_tree"
181
+
182
+ def interpret(
183
+ self,
184
+ X_train,
185
+ y_train,
186
+ X_validation,
187
+ y_validation,
188
+ model_file_path,
189
+ learner_name,
190
+ target_name=None,
191
+ class_names=None,
192
+ metric_name=None,
193
+ ml_task=None,
194
+ explain_level=2,
195
+ ):
196
+ super(DecisionTreeRegressorAlgorithm, self).interpret(
197
+ X_train,
198
+ y_train,
199
+ X_validation,
200
+ y_validation,
201
+ model_file_path,
202
+ learner_name,
203
+ target_name,
204
+ class_names,
205
+ metric_name,
206
+ ml_task,
207
+ explain_level,
208
+ )
209
+ if explain_level == 0:
210
+ return
211
+ with warnings.catch_warnings():
212
+ warnings.simplefilter(action="ignore")
213
+ try:
214
+ # 250 is hard limit for number of points used in visualization
215
+ # if too many points are used then final SVG plot is very large (can be > 100MB)
216
+ if X_train.shape[0] > 250:
217
+ x, _, y, _ = subsample(X_train, y_train, REGRESSION, 250)
218
+ viz = dtreeviz(
219
+ self.model,
220
+ x,
221
+ y,
222
+ target_name="target",
223
+ feature_names=x.columns,
224
+ )
225
+ else:
226
+ viz = dtreeviz.model(
227
+ self.model,
228
+ X_train,
229
+ y_train,
230
+ target_name="target",
231
+ feature_names=X_train.columns,
232
+ )
233
+ tree_file_plot = os.path.join(
234
+ model_file_path, learner_name + "_tree.svg"
235
+ )
236
+ viz.view().save(tree_file_plot)
237
+ except Exception as e:
238
+ logger.info(
239
+ f"Problem when visuzalizin decision tree regressor. {str(e)}"
240
+ )
241
+
242
+ save_rules(self.model, X_train.columns, None, model_file_path, learner_name)
243
+
244
+
245
+ dt_params = {"criterion": ["gini", "entropy"], "max_depth": [2, 3, 4]}
246
+
247
+ classification_default_params = {"criterion": "gini", "max_depth": 3}
248
+
249
+ additional = {
250
+ "trees_in_step": 1,
251
+ "train_cant_improve_limit": 0,
252
+ "max_steps": 1,
253
+ "max_rows_limit": None,
254
+ "max_cols_limit": None,
255
+ }
256
+ required_preprocessing = [
257
+ "missing_values_inputation",
258
+ "convert_categorical",
259
+ "datetime_transform",
260
+ "text_transform",
261
+ "target_as_integer",
262
+ ]
263
+
264
+ AlgorithmsRegistry.add(
265
+ BINARY_CLASSIFICATION,
266
+ DecisionTreeAlgorithm,
267
+ dt_params,
268
+ required_preprocessing,
269
+ additional,
270
+ classification_default_params,
271
+ )
272
+
273
+ AlgorithmsRegistry.add(
274
+ MULTICLASS_CLASSIFICATION,
275
+ DecisionTreeAlgorithm,
276
+ dt_params,
277
+ required_preprocessing,
278
+ additional,
279
+ classification_default_params,
280
+ )
281
+
282
+ dt_regression_params = {
283
+ "criterion": [
284
+ "squared_error",
285
+ "friedman_mse",
286
+ ], # remove "mae" because it slows down a lot https://github.com/scikit-learn/scikit-learn/issues/9626
287
+ "max_depth": [2, 3, 4],
288
+ }
289
+ regression_required_preprocessing = [
290
+ "missing_values_inputation",
291
+ "convert_categorical",
292
+ "datetime_transform",
293
+ "text_transform",
294
+ ]
295
+
296
+ regression_default_params = {"criterion": "squared_error", "max_depth": 3}
297
+
298
+ AlgorithmsRegistry.add(
299
+ REGRESSION,
300
+ DecisionTreeRegressorAlgorithm,
301
+ dt_regression_params,
302
+ regression_required_preprocessing,
303
+ additional,
304
+ regression_default_params,
305
+ )
@@ -0,0 +1,176 @@
1
+ import logging
2
+
3
+ import sklearn
4
+ from sklearn.base import ClassifierMixin, RegressorMixin
5
+ from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor
6
+
7
+ from supervised.algorithms.registry import (
8
+ BINARY_CLASSIFICATION,
9
+ MULTICLASS_CLASSIFICATION,
10
+ REGRESSION,
11
+ AlgorithmsRegistry,
12
+ )
13
+ from supervised.algorithms.sklearn import (
14
+ SklearnTreesEnsembleClassifierAlgorithm,
15
+ SklearnTreesEnsembleRegressorAlgorithm,
16
+ )
17
+ from supervised.utils.config import LOG_LEVEL
18
+
19
+ logger = logging.getLogger(__name__)
20
+ logger.setLevel(LOG_LEVEL)
21
+
22
+
23
+ class ExtraTreesAlgorithm(ClassifierMixin, SklearnTreesEnsembleClassifierAlgorithm):
24
+ algorithm_name = "Extra Trees Classifier"
25
+ algorithm_short_name = "Extra Trees"
26
+
27
+ def __init__(self, params):
28
+ super(ExtraTreesAlgorithm, self).__init__(params)
29
+ logger.debug("ExtraTreesAlgorithm.__init__")
30
+
31
+ self.library_version = sklearn.__version__
32
+ self.trees_in_step = additional.get("trees_in_step", 100)
33
+ self.max_steps = additional.get("max_steps", 50)
34
+ self.early_stopping_rounds = additional.get("early_stopping_rounds", 50)
35
+ self.model = ExtraTreesClassifier(
36
+ n_estimators=self.trees_in_step,
37
+ criterion=params.get("criterion", "gini"),
38
+ max_features=params.get("max_features", 0.8),
39
+ max_depth=params.get("max_depth", 6),
40
+ min_samples_split=params.get("min_samples_split", 4),
41
+ min_samples_leaf=params.get("min_samples_leaf", 1),
42
+ warm_start=True,
43
+ n_jobs=params.get("n_jobs", -1),
44
+ random_state=params.get("seed", 1),
45
+ )
46
+ self.max_steps = self.params.get("max_steps", self.max_steps)
47
+
48
+ def file_extension(self):
49
+ return "extra_trees"
50
+
51
+
52
+ class ExtraTreesRegressorAlgorithm(
53
+ RegressorMixin, SklearnTreesEnsembleRegressorAlgorithm
54
+ ):
55
+ algorithm_name = "Extra Trees Regressor"
56
+ algorithm_short_name = "Extra Trees"
57
+
58
+ def __init__(self, params):
59
+ super(ExtraTreesRegressorAlgorithm, self).__init__(params)
60
+ logger.debug("ExtraTreesRegressorAlgorithm.__init__")
61
+
62
+ self.library_version = sklearn.__version__
63
+ self.trees_in_step = regression_additional.get("trees_in_step", 100)
64
+ self.max_steps = regression_additional.get("max_steps", 50)
65
+ self.early_stopping_rounds = regression_additional.get(
66
+ "early_stopping_rounds", 50
67
+ )
68
+ self.model = ExtraTreesRegressor(
69
+ n_estimators=self.trees_in_step,
70
+ criterion=params.get("criterion", "squared_error"),
71
+ max_features=params.get("max_features", 0.6),
72
+ max_depth=params.get("max_depth", 6),
73
+ min_samples_split=params.get("min_samples_split", 30),
74
+ min_samples_leaf=params.get("min_samples_leaf", 1),
75
+ warm_start=True,
76
+ n_jobs=params.get("n_jobs", -1),
77
+ random_state=params.get("seed", 1),
78
+ )
79
+ self.max_steps = self.params.get("max_steps", self.max_steps)
80
+
81
+ def file_extension(self):
82
+ return "extra_trees"
83
+
84
+
85
+ # For binary classification target should be 0, 1. There should be no NaNs in target.
86
+ et_params = {
87
+ "criterion": ["gini", "entropy"],
88
+ "max_features": [0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
89
+ "min_samples_split": [10, 20, 30, 40, 50],
90
+ "max_depth": [3, 4, 5, 6, 7],
91
+ }
92
+
93
+ classification_default_params = {
94
+ "criterion": "gini",
95
+ "max_features": 0.9,
96
+ "min_samples_split": 30,
97
+ "max_depth": 4,
98
+ }
99
+
100
+ additional = {
101
+ "trees_in_step": 100,
102
+ "max_steps": 50,
103
+ "early_stopping_rounds": 50,
104
+ "max_rows_limit": None,
105
+ "max_cols_limit": None,
106
+ }
107
+ required_preprocessing = [
108
+ "missing_values_inputation",
109
+ "convert_categorical",
110
+ "datetime_transform",
111
+ "text_transform",
112
+ "target_as_integer",
113
+ ]
114
+
115
+ AlgorithmsRegistry.add(
116
+ BINARY_CLASSIFICATION,
117
+ ExtraTreesAlgorithm,
118
+ et_params,
119
+ required_preprocessing,
120
+ additional,
121
+ classification_default_params,
122
+ )
123
+
124
+ AlgorithmsRegistry.add(
125
+ MULTICLASS_CLASSIFICATION,
126
+ ExtraTreesAlgorithm,
127
+ et_params,
128
+ required_preprocessing,
129
+ additional,
130
+ classification_default_params,
131
+ )
132
+
133
+
134
+ #
135
+ # REGRESSION
136
+ #
137
+
138
+ regression_et_params = {
139
+ "criterion": [
140
+ "squared_error"
141
+ ], # remove "mae" because it slows down a lot https://github.com/scikit-learn/scikit-learn/issues/9626
142
+ "max_features": [0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
143
+ "min_samples_split": [10, 20, 30, 40, 50],
144
+ "max_depth": [3, 4, 5, 6, 7],
145
+ }
146
+
147
+ regression_default_params = {
148
+ "criterion": "squared_error",
149
+ "max_features": 0.9,
150
+ "min_samples_split": 30,
151
+ "max_depth": 4,
152
+ }
153
+
154
+ regression_additional = {
155
+ "trees_in_step": 100,
156
+ "max_steps": 50,
157
+ "early_stopping_rounds": 50,
158
+ "max_rows_limit": None,
159
+ "max_cols_limit": None,
160
+ }
161
+ regression_required_preprocessing = [
162
+ "missing_values_inputation",
163
+ "convert_categorical",
164
+ "datetime_transform",
165
+ "text_transform",
166
+ "target_scale",
167
+ ]
168
+
169
+ AlgorithmsRegistry.add(
170
+ REGRESSION,
171
+ ExtraTreesRegressorAlgorithm,
172
+ regression_et_params,
173
+ regression_required_preprocessing,
174
+ regression_additional,
175
+ regression_default_params,
176
+ )
@@ -0,0 +1,28 @@
1
+ import logging
2
+
3
+ from supervised.algorithms.registry import BINARY_CLASSIFICATION, AlgorithmsRegistry
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ from supervised.exceptions import AutoMLException
8
+
9
+
10
+ class AlgorithmFactory(object):
11
+ @classmethod
12
+ def get_algorithm(cls, params):
13
+ alg_type = params.get("model_type", "Xgboost")
14
+ ml_task = params.get("ml_task", BINARY_CLASSIFICATION)
15
+
16
+ try:
17
+ Algorithm = AlgorithmsRegistry.get_algorithm_class(ml_task, alg_type)
18
+ return Algorithm(params)
19
+ except Exception as e:
20
+ raise AutoMLException(f"Cannot get algorithm class. {str(e)}")
21
+
22
+ @classmethod
23
+ def load(cls, json_desc, learner_path, lazy_load):
24
+ learner = AlgorithmFactory.get_algorithm(json_desc.get("params"))
25
+ learner.set_params(json_desc, learner_path)
26
+ if not lazy_load:
27
+ learner.reload()
28
+ return learner
@@ -0,0 +1,137 @@
1
+ import logging
2
+
3
+ import sklearn
4
+ from sklearn.base import ClassifierMixin, RegressorMixin
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
7
+
8
+ from supervised.algorithms.registry import (
9
+ BINARY_CLASSIFICATION,
10
+ MULTICLASS_CLASSIFICATION,
11
+ REGRESSION,
12
+ AlgorithmsRegistry,
13
+ )
14
+ from supervised.algorithms.sklearn import SklearnAlgorithm
15
+ from supervised.utils.config import LOG_LEVEL
16
+
17
+ logger = logging.getLogger(__name__)
18
+ logger.setLevel(LOG_LEVEL)
19
+
20
+
21
+ KNN_ROWS_LIMIT = 1000
22
+
23
+
24
+ class KNNFit(SklearnAlgorithm):
25
+ def file_extension(self):
26
+ return "k_neighbors"
27
+
28
+ def is_fitted(self):
29
+ return (
30
+ hasattr(self.model, "n_samples_fit_")
31
+ and self.model.n_samples_fit_ is not None
32
+ and self.model.n_samples_fit_ > 0
33
+ )
34
+
35
+ def fit(
36
+ self,
37
+ X,
38
+ y,
39
+ sample_weight=None,
40
+ X_validation=None,
41
+ y_validation=None,
42
+ sample_weight_validation=None,
43
+ log_to_file=None,
44
+ max_time=None,
45
+ ):
46
+ rows_limit = self.params.get("rows_limit", KNN_ROWS_LIMIT)
47
+ if X.shape[0] > rows_limit:
48
+ X1, _, y1, _ = train_test_split(
49
+ X, y, train_size=rows_limit, stratify=y, random_state=1234
50
+ )
51
+ self.model.fit(X1, y1)
52
+ else:
53
+ self.model.fit(X, y)
54
+
55
+ @property
56
+ def _classes(self):
57
+ # Returns the unique classes based on the fitted model
58
+ if hasattr(self.model, "classes_"):
59
+ return self.model.classes_
60
+ else:
61
+ return None
62
+
63
+
64
+ class KNeighborsAlgorithm(ClassifierMixin, KNNFit):
65
+ algorithm_name = "k-Nearest Neighbors"
66
+ algorithm_short_name = "Nearest Neighbors"
67
+
68
+ def __init__(self, params):
69
+ super(KNeighborsAlgorithm, self).__init__(params)
70
+ logger.debug("KNeighborsAlgorithm.__init__")
71
+ self.library_version = sklearn.__version__
72
+ self.max_iters = 1
73
+ self.model = KNeighborsClassifier(
74
+ n_neighbors=params.get("n_neighbors", 3),
75
+ weights=params.get("weights", "uniform"),
76
+ algorithm="kd_tree",
77
+ n_jobs=params.get("n_jobs", -1),
78
+ )
79
+
80
+
81
+ class KNeighborsRegressorAlgorithm(RegressorMixin, KNNFit):
82
+ algorithm_name = "k-Nearest Neighbors"
83
+ algorithm_short_name = "Nearest Neighbors"
84
+
85
+ def __init__(self, params):
86
+ super(KNeighborsRegressorAlgorithm, self).__init__(params)
87
+ logger.debug("KNeighborsRegressorAlgorithm.__init__")
88
+ self.library_version = sklearn.__version__
89
+ self.max_iters = 1
90
+ self.model = KNeighborsRegressor(
91
+ n_neighbors=params.get("n_neighbors", 3),
92
+ weights=params.get("weights", "uniform"),
93
+ algorithm="ball_tree",
94
+ n_jobs=params.get("n_jobs", -1),
95
+ )
96
+
97
+
98
+ knn_params = {"n_neighbors": [3, 5, 7], "weights": ["uniform", "distance"]}
99
+
100
+ default_params = {"n_neighbors": 5, "weights": "uniform"}
101
+
102
+ additional = {"max_rows_limit": 100000, "max_cols_limit": 100}
103
+
104
+ required_preprocessing = [
105
+ "missing_values_inputation",
106
+ "convert_categorical",
107
+ "datetime_transform",
108
+ "text_transform",
109
+ "scale",
110
+ "target_as_integer",
111
+ ]
112
+
113
+ AlgorithmsRegistry.add(
114
+ BINARY_CLASSIFICATION,
115
+ KNeighborsAlgorithm,
116
+ knn_params,
117
+ required_preprocessing,
118
+ additional,
119
+ default_params,
120
+ )
121
+ AlgorithmsRegistry.add(
122
+ MULTICLASS_CLASSIFICATION,
123
+ KNeighborsAlgorithm,
124
+ knn_params,
125
+ required_preprocessing,
126
+ additional,
127
+ default_params,
128
+ )
129
+
130
+ AlgorithmsRegistry.add(
131
+ REGRESSION,
132
+ KNeighborsRegressorAlgorithm,
133
+ knn_params,
134
+ required_preprocessing,
135
+ additional,
136
+ default_params,
137
+ )