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,117 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from supervised.preprocessing.label_binarizer import LabelBinarizer
5
+ from supervised.preprocessing.label_encoder import LabelEncoder
6
+ from supervised.preprocessing.preprocessing_utils import PreprocessingUtils
7
+
8
+
9
+ class PreprocessingCategorical(object):
10
+ CONVERT_ONE_HOT = "categorical_to_onehot"
11
+ CONVERT_INTEGER = "categorical_to_int"
12
+
13
+ FEW_CATEGORIES = "few_categories"
14
+ MANY_CATEGORIES = "many_categories"
15
+
16
+ def __init__(self, columns=[], method=CONVERT_INTEGER):
17
+ self._convert_method = method
18
+ self._convert_params = {}
19
+ self._columns = columns
20
+ self._enc = None
21
+
22
+ def fit(self, X, y=None):
23
+ self._fit_categorical_convert(X)
24
+
25
+ def _fit_categorical_convert(self, X):
26
+ for column in self._columns:
27
+ if PreprocessingUtils.get_type(X[column]) != PreprocessingUtils.CATEGORICAL:
28
+ # no need to convert, already a number
29
+ continue
30
+ # limit categories - it is needed when doing one hot encoding
31
+ # this code is also used in predict.py file
32
+ # and transform_utils.py
33
+ # TODO it needs refactoring !!!
34
+ too_much_categories = len(np.unique(list(X[column].values))) > 200
35
+ lbl = None
36
+ if (
37
+ self._convert_method == PreprocessingCategorical.CONVERT_ONE_HOT
38
+ and not too_much_categories
39
+ ):
40
+ lbl = LabelBinarizer()
41
+ lbl.fit(X, column)
42
+ else:
43
+ lbl = LabelEncoder()
44
+ lbl.fit(X[column])
45
+
46
+ if lbl is not None:
47
+ self._convert_params[column] = lbl.to_json()
48
+
49
+ def transform(self, X):
50
+ for column, lbl_params in self._convert_params.items():
51
+ if "unique_values" in lbl_params and "new_columns" in lbl_params:
52
+ # convert to one hot
53
+ lbl = LabelBinarizer()
54
+ lbl.from_json(lbl_params)
55
+ X = lbl.transform(X, column)
56
+ else:
57
+ # convert to integer
58
+ lbl = LabelEncoder()
59
+ lbl.from_json(lbl_params)
60
+ transformed_values = lbl.transform(X.loc[:, column])
61
+ col_dtype = X.loc[:, column].dtype
62
+ # check for pandas FutureWarning: Setting an item
63
+ # of incompatible dtype is deprecated and will raise
64
+ # in a future error of pandas.
65
+ if transformed_values.dtype != col_dtype and \
66
+ (col_dtype == bool or col_dtype == int):
67
+ X = X.astype({column: transformed_values.dtype})
68
+ # pandas string/categorical extension dtypes reject integer arrays.
69
+ if isinstance(col_dtype, pd.CategoricalDtype) or pd.api.types.is_string_dtype(col_dtype):
70
+ X[column] = X[column].astype('object')
71
+ X.loc[:, column] = transformed_values
72
+
73
+ return X
74
+
75
+ def inverse_transform(self, X):
76
+ for column, lbl_params in self._convert_params.items():
77
+ if "unique_values" in lbl_params and "new_columns" in lbl_params:
78
+ # convert to one hot
79
+ lbl = LabelBinarizer()
80
+ lbl.from_json(lbl_params)
81
+ X = lbl.inverse_transform(X, column) # should raise exception
82
+ else:
83
+ # convert to integer
84
+ lbl = LabelEncoder()
85
+ lbl.from_json(lbl_params)
86
+ transformed_values = lbl.inverse_transform(X.loc[:, column])
87
+ # check for pandas FutureWarning: Setting an item
88
+ # of incompatible dtype is deprecated and will raise
89
+ # in a future error of pandas.
90
+ if transformed_values.dtype != X.loc[:, column].dtype and \
91
+ (X.loc[:, column].dtype == bool or X.loc[:, column].dtype == int):
92
+ X = X.astype({column: transformed_values.dtype})
93
+ X.loc[:, column] = transformed_values
94
+
95
+ return X
96
+
97
+ def to_json(self):
98
+ params = {}
99
+
100
+ if len(self._convert_params) == 0:
101
+ return {}
102
+ params = {
103
+ "convert_method": self._convert_method,
104
+ "convert_params": self._convert_params,
105
+ "columns": self._columns,
106
+ }
107
+ return params
108
+
109
+ def from_json(self, params):
110
+ if params is not None:
111
+ self._convert_method = params.get("convert_method", None)
112
+ self._columns = params.get("columns", [])
113
+ self._convert_params = params.get("convert_params", {})
114
+
115
+ else:
116
+ self._convert_method, self._convert_params = None, None
117
+ self._columns = []
@@ -0,0 +1,97 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from supervised.preprocessing.preprocessing_utils import PreprocessingUtils
5
+
6
+
7
+ class PreprocessingMissingValues(object):
8
+ FILL_NA_MIN = "na_fill_min_1"
9
+ FILL_NA_MEAN = "na_fill_mean"
10
+ FILL_NA_MEDIAN = "na_fill_median"
11
+ FILL_DATETIME = "na_fill_datetime"
12
+
13
+ NA_EXCLUDE = "na_exclude"
14
+ MISSING_VALUE = "_missing_value_"
15
+ REMOVE_COLUMN = "remove_column"
16
+
17
+ def __init__(self, columns=[], na_fill_method=FILL_NA_MEDIAN):
18
+ self._columns = columns
19
+ # fill method
20
+ self._na_fill_method = na_fill_method
21
+ # fill parameters stored as a dict, feature -> fill value
22
+ self._na_fill_params = {}
23
+ self._datetime_columns = []
24
+
25
+ def fit(self, X):
26
+ X = self._fit_na_fill(X)
27
+
28
+ def _fit_na_fill(self, X):
29
+ for column in self._columns:
30
+ if np.sum(pd.isnull(X[column]) == True) == 0:
31
+ continue
32
+ self._na_fill_params[column] = self._get_fill_value(X[column])
33
+ if PreprocessingUtils.get_type(X[column]) == PreprocessingUtils.DATETIME:
34
+ self._datetime_columns += [column]
35
+
36
+ def _get_fill_value(self, x):
37
+ # categorical type
38
+ if PreprocessingUtils.get_type(x) == PreprocessingUtils.CATEGORICAL:
39
+ if self._na_fill_method == PreprocessingMissingValues.FILL_NA_MIN:
40
+ return (
41
+ PreprocessingMissingValues.MISSING_VALUE
42
+ ) # add new categorical value
43
+ return PreprocessingUtils.get_most_frequent(x)
44
+ # datetime
45
+ if PreprocessingUtils.get_type(x) == PreprocessingUtils.DATETIME:
46
+ return PreprocessingUtils.get_most_frequent(x)
47
+ # text
48
+ if PreprocessingUtils.get_type(x) == PreprocessingUtils.TEXT:
49
+ return PreprocessingMissingValues.MISSING_VALUE
50
+
51
+ # numerical type
52
+ if self._na_fill_method == PreprocessingMissingValues.FILL_NA_MIN:
53
+ return PreprocessingUtils.get_min(x) - 1.0
54
+ if self._na_fill_method == PreprocessingMissingValues.FILL_NA_MEAN:
55
+ return PreprocessingUtils.get_mean(x)
56
+ return PreprocessingUtils.get_median(x)
57
+
58
+ def transform(self, X):
59
+ X = self._transform_na_fill(X)
60
+ # this is additional run through columns,
61
+ # in case of transforming data with new columns with missing values
62
+ # X = self._make_sure_na_filled(X) # disbaled for now
63
+ return X
64
+
65
+ def _transform_na_fill(self, X):
66
+ for column, value in self._na_fill_params.items():
67
+ ind = pd.isnull(X.loc[:, column])
68
+ X.loc[ind, column] = value
69
+ return X
70
+
71
+ def _make_sure_na_filled(self, X):
72
+ self._fit_na_fill(X)
73
+ return self._transform_na_fill(X)
74
+
75
+ def to_json(self):
76
+ # prepare json with all parameters
77
+ if len(self._na_fill_params) == 0:
78
+ return {}
79
+ params = {
80
+ "fill_method": self._na_fill_method,
81
+ "fill_params": self._na_fill_params,
82
+ "datetime_columns": list(self._datetime_columns),
83
+ }
84
+ for col in self._datetime_columns:
85
+ params["fill_params"][col] = str(params["fill_params"][col])
86
+ return params
87
+
88
+ def from_json(self, params):
89
+ if params is not None:
90
+ self._na_fill_method = params.get("fill_method", None)
91
+ self._na_fill_params = params.get("fill_params", {})
92
+ self._datetime_columns = params.get("datetime_columns", [])
93
+ for col in self._datetime_columns:
94
+ self._na_fill_params[col] = pd.to_datetime(self._na_fill_params[col])
95
+ else:
96
+ self._na_fill_method, self._na_fill_params = None, None
97
+ self._datetime_columns = []
@@ -0,0 +1,136 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from scipy import stats
4
+ from sklearn import preprocessing
5
+
6
+
7
+ class PreprocessingUtilsException(Exception):
8
+ pass
9
+
10
+
11
+ class PreprocessingUtils(object):
12
+ CATEGORICAL = "categorical"
13
+ CONTINOUS = "continous"
14
+ DISCRETE = "discrete"
15
+ DATETIME = "datetime"
16
+ TEXT = "text"
17
+
18
+ @staticmethod
19
+ def get_type(x):
20
+ if len(x.shape) > 1:
21
+ if x.shape[1] != 1:
22
+ raise PreprocessingUtilsException(
23
+ "Please select one column to get its type"
24
+ )
25
+ col_type = str(x.dtype)
26
+
27
+ data_type = PreprocessingUtils.CATEGORICAL
28
+ if col_type.startswith("float"):
29
+ data_type = PreprocessingUtils.CONTINOUS
30
+ elif col_type.startswith("int") or col_type.startswith("uint"):
31
+ data_type = PreprocessingUtils.DISCRETE
32
+ elif col_type.startswith("datetime"):
33
+ data_type = PreprocessingUtils.DATETIME
34
+ elif col_type.startswith("category"):
35
+ # do not check the additional condition for text feature
36
+ # treat it as categorical
37
+ return PreprocessingUtils.CATEGORICAL
38
+
39
+ if data_type == PreprocessingUtils.CATEGORICAL:
40
+ # check maybe this categorical is a text
41
+ # it is a text, if:
42
+ # has more than 200 unique values
43
+ # more than half of rows is unique
44
+ unique_cnt = len(np.unique(x[~pd.isnull(x)]))
45
+ if unique_cnt > 200 and unique_cnt > int(0.5 * x.shape[0]):
46
+ data_type = PreprocessingUtils.TEXT
47
+
48
+ return data_type
49
+
50
+ @staticmethod
51
+ def is_categorical(x_org):
52
+ x = x_org[~pd.isnull(x_org)]
53
+ return PreprocessingUtils.get_type(x) == PreprocessingUtils.CATEGORICAL
54
+
55
+ @staticmethod
56
+ def is_datetime(x_org):
57
+ x = x_org[~pd.isnull(x_org)]
58
+ return PreprocessingUtils.get_type(x) == PreprocessingUtils.DATETIME
59
+
60
+ @staticmethod
61
+ def is_text(x_org):
62
+ x = x_org[~pd.isnull(x_org)]
63
+ return PreprocessingUtils.get_type(x) == PreprocessingUtils.TEXT
64
+
65
+ @staticmethod
66
+ def is_0_1(x_org):
67
+ x = x_org[~pd.isnull(x_org)]
68
+ u = np.unique(x)
69
+ if len(u) != 2:
70
+ return False
71
+ return 0 in u and 1 in u
72
+
73
+ @staticmethod
74
+ def num_class(x_org):
75
+ x = x_org[~pd.isnull(x_org)]
76
+ u = np.unique(x)
77
+ return len(u)
78
+
79
+ @staticmethod
80
+ def is_scale_needed(x_org):
81
+ x = x_org[~pd.isnull(x_org)]
82
+ abs_avg = np.abs(np.mean(x))
83
+ stddev = np.std(x)
84
+ if abs_avg > 0.5 or stddev > 1.5:
85
+ return True
86
+ return False
87
+
88
+ @staticmethod
89
+ def is_log_scale_needed(x_org):
90
+ x_full = np.array(x_org[~pd.isnull(x_org)])
91
+ # first scale on raw data
92
+ x = preprocessing.scale(x_full)
93
+ # second scale on log data
94
+ x_log = preprocessing.scale(np.log(x_full - np.min(x_full) + 1))
95
+
96
+ # the old approach, let's check how new approach will work
97
+ # original_skew = np.abs(stats.skew(x))
98
+ # log_skew = np.abs(stats.skew(x_log))
99
+ # return log_skew < original_skew
100
+ ########################################################################
101
+ # p is probability of being normal distributions
102
+ k2, p1 = stats.normaltest(x)
103
+ k2, p2 = stats.normaltest(x_log)
104
+
105
+ return p2 > p1
106
+
107
+ @staticmethod
108
+ def is_na(x):
109
+ return np.sum(pd.isnull(x) == True) > 0
110
+
111
+ @staticmethod
112
+ def get_most_frequent(x):
113
+ a = x.value_counts()
114
+ first = sorted(dict(a).items(), key=lambda x: -x[1])[0]
115
+ return first[0]
116
+
117
+ @staticmethod
118
+ def get_min(x):
119
+ v = np.amin(np.nanmin(x))
120
+ if pd.isnull(v):
121
+ return 0
122
+ return float(v)
123
+
124
+ @staticmethod
125
+ def get_mean(x):
126
+ v = np.nanmean(x)
127
+ if pd.isnull(v):
128
+ return 0
129
+ return float(v)
130
+
131
+ @staticmethod
132
+ def get_median(x):
133
+ v = np.nanmedian(x)
134
+ if pd.isnull(v):
135
+ return 0
136
+ return float(v)
@@ -0,0 +1,92 @@
1
+ import numpy as np
2
+ from sklearn import preprocessing
3
+
4
+
5
+ class Scale(object):
6
+ SCALE_NORMAL = "scale_normal"
7
+ SCALE_LOG_AND_NORMAL = "scale_log_and_normal"
8
+
9
+ def __init__(self, columns=[], scale_method=SCALE_NORMAL):
10
+ self.scale_method = scale_method
11
+ self.columns = columns
12
+ self.scale = preprocessing.StandardScaler(
13
+ copy=True, with_mean=True, with_std=True
14
+ )
15
+ self.X_min_values = None # it is used in SCALE_LOG_AND_NORMAL
16
+
17
+ def fit(self, X):
18
+ if len(self.columns):
19
+ for c in self.columns:
20
+ X[c] = X[c].astype(float)
21
+
22
+ if self.scale_method == self.SCALE_NORMAL:
23
+ self.scale.fit(X[self.columns])
24
+ elif self.scale_method == self.SCALE_LOG_AND_NORMAL:
25
+ self.X_min_values = np.min(X[self.columns], axis=0)
26
+ self.scale.fit(np.log(X[self.columns] - self.X_min_values + 1))
27
+
28
+ def transform(self, X):
29
+ if len(self.columns):
30
+ for c in self.columns:
31
+ X[c] = X[c].astype(float)
32
+ if self.scale_method == self.SCALE_NORMAL:
33
+ X.loc[:, self.columns] = self.scale.transform(X[self.columns])
34
+ elif self.scale_method == self.SCALE_LOG_AND_NORMAL:
35
+ X[self.columns] = np.log(
36
+ np.clip(
37
+ X[self.columns] - self.X_min_values + 1, a_min=1, a_max=None
38
+ )
39
+ )
40
+ X.loc[:, self.columns] = self.scale.transform(X[self.columns])
41
+ return X
42
+
43
+ def inverse_transform(self, X):
44
+ if len(self.columns):
45
+ if self.scale_method == self.SCALE_NORMAL:
46
+ X.loc[:, self.columns] = self.scale.inverse_transform(X[self.columns])
47
+ elif self.scale_method == self.SCALE_LOG_AND_NORMAL:
48
+ X[self.columns] = X[self.columns].astype("float64")
49
+
50
+ X[self.columns] = self.scale.inverse_transform(X[self.columns])
51
+ X[self.columns] = np.exp(X[self.columns])
52
+
53
+ X.loc[:, self.columns] += self.X_min_values - 1
54
+ return X
55
+
56
+ def to_json(self):
57
+ if len(self.columns) == 0:
58
+ return None
59
+ data_json = {
60
+ "scale": list(self.scale.scale_),
61
+ "mean": list(self.scale.mean_),
62
+ "var": list(self.scale.var_),
63
+ "n_samples_seen": int(self.scale.n_samples_seen_),
64
+ "n_features_in": int(self.scale.n_features_in_),
65
+ "columns": self.columns,
66
+ "scale_method": self.scale_method,
67
+ }
68
+ if self.X_min_values is not None:
69
+ data_json["X_min_values"] = list(self.X_min_values)
70
+ return data_json
71
+
72
+ def from_json(self, data_json):
73
+ self.scale = preprocessing.StandardScaler(
74
+ copy=True, with_mean=True, with_std=True
75
+ )
76
+ self.scale.scale_ = data_json.get("scale")
77
+ if self.scale.scale_ is not None:
78
+ self.scale.scale_ = np.array(self.scale.scale_)
79
+ self.scale.mean_ = data_json.get("mean")
80
+ if self.scale.mean_ is not None:
81
+ self.scale.mean_ = np.array(self.scale.mean_)
82
+ self.scale.var_ = data_json.get("var")
83
+ if self.scale.var_ is not None:
84
+ self.scale.var_ = np.array(self.scale.var_)
85
+ self.scale.n_samples_seen_ = int(data_json.get("n_samples_seen"))
86
+ self.scale.n_features_in_ = int(data_json.get("n_features_in"))
87
+ self.columns = data_json.get("columns", [])
88
+ self.scale.feature_names_in_ = data_json.get("columns")
89
+ self.scale_method = data_json.get("scale_method")
90
+ self.X_min_values = data_json.get("X_min_values")
91
+ if self.X_min_values is not None:
92
+ self.X_min_values = np.array(self.X_min_values)
@@ -0,0 +1,73 @@
1
+ import warnings
2
+ import numpy as np
3
+ import pandas as pd
4
+ from sklearn.feature_extraction.text import TfidfVectorizer
5
+
6
+
7
+ class TextTransformer(object):
8
+ def __init__(self):
9
+ self._new_columns = []
10
+ self._old_column = None
11
+ self._max_features = 100
12
+ self._vectorizer = None
13
+
14
+ def fit(self, X, column):
15
+ self._old_column = column
16
+ self._vectorizer = TfidfVectorizer(
17
+ analyzer="word",
18
+ stop_words="english",
19
+ lowercase=True,
20
+ max_features=self._max_features,
21
+ )
22
+
23
+ x = X[column][~pd.isnull(X[column])]
24
+ self._vectorizer.fit(x)
25
+ for f in list(self._vectorizer.get_feature_names_out()):
26
+ new_col = self._old_column + "_" + f
27
+ self._new_columns += [new_col]
28
+
29
+ def transform(self, X):
30
+ with warnings.catch_warnings():
31
+ warnings.simplefilter(
32
+ action="ignore", category=pd.errors.PerformanceWarning
33
+ )
34
+ ii = ~pd.isnull(X[self._old_column])
35
+ x = X[self._old_column][ii]
36
+ vect = self._vectorizer.transform(x)
37
+
38
+ for f in self._new_columns:
39
+ X[f] = 0.0
40
+
41
+ X.loc[ii, self._new_columns] = vect.toarray()
42
+ X.drop(self._old_column, axis=1, inplace=True)
43
+ return X
44
+
45
+ def to_json(self):
46
+ for k in self._vectorizer.vocabulary_.keys():
47
+ self._vectorizer.vocabulary_[k] = int(self._vectorizer.vocabulary_[k])
48
+
49
+ data_json = {
50
+ "new_columns": list(self._new_columns),
51
+ "old_column": self._old_column,
52
+ "vocabulary": self._vectorizer.vocabulary_,
53
+ "fixed_vocabulary": self._vectorizer.fixed_vocabulary_,
54
+ "idf": list(self._vectorizer.idf_),
55
+ }
56
+ return data_json
57
+
58
+ def from_json(self, data_json):
59
+ self._new_columns = data_json.get("new_columns", None)
60
+ self._old_column = data_json.get("old_column", None)
61
+ vocabulary = data_json.get("vocabulary")
62
+ fixed_vocabulary = data_json.get("fixed_vocabulary")
63
+ idf = data_json.get("idf")
64
+ if vocabulary is not None and fixed_vocabulary is not None and idf is not None:
65
+ self._vectorizer = TfidfVectorizer(
66
+ analyzer="word",
67
+ stop_words="english",
68
+ lowercase=True,
69
+ max_features=self._max_features,
70
+ )
71
+ self._vectorizer.vocabulary_ = vocabulary
72
+ self._vectorizer.fixed_vocabulary_ = fixed_vocabulary
73
+ self._vectorizer.idf_ = np.array(idf)
File without changes
@@ -0,0 +1,64 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from supervised.algorithms.registry import (
5
+ BINARY_CLASSIFICATION,
6
+ MULTICLASS_CLASSIFICATION,
7
+ REGRESSION,
8
+ )
9
+ from supervised.preprocessing.encoding_selector import EncodingSelector
10
+ from supervised.preprocessing.preprocessing_utils import PreprocessingUtils
11
+
12
+
13
+ class DataInfo:
14
+ @staticmethod
15
+ def compute(X, y, machinelearning_task):
16
+ columns_info = {}
17
+ for col in X.columns:
18
+ columns_info[col] = []
19
+ #
20
+ empty_column = np.sum(pd.isnull(X[col]) == True) == X.shape[0]
21
+ if empty_column:
22
+ columns_info[col] += ["empty_column"]
23
+ continue
24
+ #
25
+ constant_column = len(np.unique(X.loc[~pd.isnull(X[col]), col])) == 1
26
+ if constant_column:
27
+ columns_info[col] += ["constant_column"]
28
+ continue
29
+ #
30
+ if PreprocessingUtils.is_na(X[col]):
31
+ columns_info[col] += ["missing_values"]
32
+ #
33
+ if PreprocessingUtils.is_categorical(X[col]):
34
+ columns_info[col] += ["categorical"]
35
+ columns_info[col] += [EncodingSelector.get(X, y, col)]
36
+ elif PreprocessingUtils.is_datetime(X[col]):
37
+ columns_info[col] += ["datetime_transform"]
38
+ elif PreprocessingUtils.is_text(X[col]):
39
+ columns_info[col] = ["text_transform"] # override other transforms
40
+ else:
41
+ # numeric type, check if scale needed
42
+ if PreprocessingUtils.is_scale_needed(X[col]):
43
+ columns_info[col] += ["scale"]
44
+
45
+ target_info = []
46
+ if machinelearning_task == BINARY_CLASSIFICATION:
47
+ if not PreprocessingUtils.is_0_1(y):
48
+ target_info += ["convert_0_1"]
49
+
50
+ if machinelearning_task == REGRESSION:
51
+ if PreprocessingUtils.is_log_scale_needed(y):
52
+ target_info += ["scale_log"]
53
+ elif PreprocessingUtils.is_scale_needed(y):
54
+ target_info += ["scale"]
55
+
56
+ num_class = None
57
+ if machinelearning_task == MULTICLASS_CLASSIFICATION:
58
+ num_class = PreprocessingUtils.num_class(y)
59
+
60
+ return {
61
+ "columns_info": columns_info,
62
+ "target_info": target_info,
63
+ "num_class": num_class,
64
+ }
@@ -0,0 +1,80 @@
1
+ import copy
2
+
3
+ import numpy as np
4
+
5
+ from supervised.algorithms.registry import AlgorithmsRegistry
6
+
7
+
8
+ class HillClimbing:
9
+
10
+ """
11
+ Example params are in JSON format:
12
+ {
13
+ "booster": ["gbtree", "gblinear"],
14
+ "objective": ["binary:logistic"],
15
+ "eval_metric": ["auc", "logloss"],
16
+ "eta": [0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05, 0.075, 0.1]
17
+ }
18
+ """
19
+
20
+ @staticmethod
21
+ def get(params, ml_task, seed=1):
22
+ np.random.seed(seed)
23
+ keys = list(params.keys())
24
+ for k in [
25
+ "num_class",
26
+ "model_type",
27
+ "seed",
28
+ "ml_task",
29
+ "explain_level",
30
+ "model_architecture_json",
31
+ "n_jobs",
32
+ "metric",
33
+ "eval_metric",
34
+ "custom_eval_metric_name",
35
+ "eval_metric_name",
36
+ ]:
37
+ if k in keys:
38
+ keys.remove(k)
39
+
40
+ model_type = params["model_type"]
41
+ if model_type == "Baseline":
42
+ return [None, None]
43
+ model_info = AlgorithmsRegistry.registry[ml_task][model_type]
44
+ model_params = model_info["params"]
45
+
46
+ permuted_keys = np.random.permutation(keys)
47
+ key_to_update = None
48
+ values = None
49
+
50
+ for key_to_update in permuted_keys:
51
+ if key_to_update not in model_params:
52
+ continue
53
+ values = model_params[key_to_update]
54
+ if len(values) > 1:
55
+ break
56
+ if values is None:
57
+ return [None, None]
58
+
59
+ left, right = None, None
60
+ for i, v in enumerate(values):
61
+ if v == params[key_to_update]:
62
+ if i + 1 < len(values):
63
+ right = values[i + 1]
64
+ if i - 1 >= 0:
65
+ left = values[i - 1]
66
+
67
+ params_1, params_2 = None, None
68
+ if left is not None:
69
+ params_1 = copy.deepcopy(params)
70
+ params_1[key_to_update] = left
71
+ if right is not None:
72
+ params_2 = copy.deepcopy(params)
73
+ params_2[key_to_update] = right
74
+
75
+ if params_1 is not None and "model_architecture_json" in params_1:
76
+ del params_1["model_architecture_json"]
77
+ if params_2 is not None and "model_architecture_json" in params_2:
78
+ del params_2["model_architecture_json"]
79
+
80
+ return [params_1, params_2]