|
| 1 | +#=============================================================================== |
| 2 | +# Copyright 2023 Intel Corporation |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +#=============================================================================== |
| 16 | + |
| 17 | +# daal4py Model builders API |
| 18 | + |
| 19 | +import numpy as np |
| 20 | +import daal4py as d4p |
| 21 | + |
| 22 | +try: |
| 23 | + from pandas import DataFrame |
| 24 | + from pandas.core.dtypes.cast import find_common_type |
| 25 | + pandas_is_imported = True |
| 26 | +except (ImportError, ModuleNotFoundError): |
| 27 | + pandas_is_imported = False |
| 28 | + |
| 29 | + |
| 30 | +def parse_dtype(dt): |
| 31 | + if dt == np.double: |
| 32 | + return "double" |
| 33 | + if dt == np.single: |
| 34 | + return "float" |
| 35 | + raise ValueError(f"Input array has unexpected dtype = {dt}") |
| 36 | + |
| 37 | + |
| 38 | +def getFPType(X): |
| 39 | + if pandas_is_imported: |
| 40 | + if isinstance(X, DataFrame): |
| 41 | + dt = find_common_type(X.dtypes.tolist()) |
| 42 | + return parse_dtype(dt) |
| 43 | + |
| 44 | + dt = getattr(X, 'dtype', None) |
| 45 | + return parse_dtype(dt) |
| 46 | + |
| 47 | + |
| 48 | +class GBTDAALBaseModel: |
| 49 | + def _get_params_from_lightgbm(self, params): |
| 50 | + self.n_classes_ = params["num_tree_per_iteration"] |
| 51 | + objective_fun = params["objective"] |
| 52 | + if self.n_classes_ <= 2: |
| 53 | + if "binary" in objective_fun: # nClasses == 1 |
| 54 | + self.n_classes_ = 2 |
| 55 | + |
| 56 | + self.n_features_in_ = params["max_feature_idx"] + 1 |
| 57 | + |
| 58 | + def _get_params_from_xgboost(self, params): |
| 59 | + self.n_classes_ = int(params["learner"]["learner_model_param"]["num_class"]) |
| 60 | + objective_fun = params["learner"]["learner_train_param"]["objective"] |
| 61 | + if self.n_classes_ <= 2: |
| 62 | + if objective_fun in ["binary:logistic", "binary:logitraw"]: |
| 63 | + self.n_classes_ = 2 |
| 64 | + |
| 65 | + self.n_features_in_ = int(params["learner"]["learner_model_param"]["num_feature"]) |
| 66 | + |
| 67 | + def _get_params_from_catboost(self, params): |
| 68 | + if 'class_params' in params['model_info']: |
| 69 | + self.n_classes_ = len(params['model_info']['class_params']['class_to_label']) |
| 70 | + self.n_features_in_ = len(params['features_info']['float_features']) |
| 71 | + |
| 72 | + def _convert_model_from_lightgbm(self, booster): |
| 73 | + lgbm_params = d4p.get_lightgbm_params(booster) |
| 74 | + self.daal_model_ = d4p.get_gbt_model_from_lightgbm(booster, lgbm_params) |
| 75 | + self._get_params_from_lightgbm(lgbm_params) |
| 76 | + |
| 77 | + def _convert_model_from_xgboost(self, booster): |
| 78 | + xgb_params = d4p.get_xgboost_params(booster) |
| 79 | + self.daal_model_ = d4p.get_gbt_model_from_xgboost(booster, xgb_params) |
| 80 | + self._get_params_from_xgboost(xgb_params) |
| 81 | + |
| 82 | + def _convert_model_from_catboost(self, booster): |
| 83 | + catboost_params = d4p.get_catboost_params(booster) |
| 84 | + self.daal_model_ = d4p.get_gbt_model_from_catboost(booster) |
| 85 | + self._get_params_from_catboost(catboost_params) |
| 86 | + |
| 87 | + def _convert_model(self, model): |
| 88 | + (submodule_name, class_name) = (model.__class__.__module__, |
| 89 | + model.__class__.__name__) |
| 90 | + self_class_name = self.__class__.__name__ |
| 91 | + |
| 92 | + # Build GBTDAALClassifier from LightGBM |
| 93 | + if (submodule_name, class_name) == ("lightgbm.sklearn", "LGBMClassifier"): |
| 94 | + if self_class_name == "GBTDAALClassifier": |
| 95 | + self._convert_model_from_lightgbm(model.booster_) |
| 96 | + else: |
| 97 | + raise TypeError(f"Only GBTDAALClassifier can be created from\ |
| 98 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 99 | + # Build GBTDAALClassifier from XGBoost |
| 100 | + elif (submodule_name, class_name) == ("xgboost.sklearn", "XGBClassifier"): |
| 101 | + if self_class_name == "GBTDAALClassifier": |
| 102 | + self._convert_model_from_xgboost(model.get_booster()) |
| 103 | + else: |
| 104 | + raise TypeError(f"Only GBTDAALClassifier can be created from\ |
| 105 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 106 | + # Build GBTDAALClassifier from CatBoost |
| 107 | + elif (submodule_name, class_name) == ("catboost.core", "CatBoostClassifier"): |
| 108 | + if self_class_name == "GBTDAALClassifier": |
| 109 | + self._convert_model_from_catboost(model) |
| 110 | + else: |
| 111 | + raise TypeError(f"Only GBTDAALClassifier can be created from\ |
| 112 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 113 | + # Build GBTDAALRegressor from LightGBM |
| 114 | + elif (submodule_name, class_name) == ("lightgbm.sklearn", "LGBMRegressor"): |
| 115 | + if self_class_name == "GBTDAALRegressor": |
| 116 | + self._convert_model_from_lightgbm(model.booster_) |
| 117 | + else: |
| 118 | + raise TypeError(f"Only GBTDAALRegressor can be created from\ |
| 119 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 120 | + # Build GBTDAALRegressor from XGBoost |
| 121 | + elif (submodule_name, class_name) == ("xgboost.sklearn", "XGBRegressor"): |
| 122 | + if self_class_name == "GBTDAALRegressor": |
| 123 | + self._convert_model_from_xgboost(model.get_booster()) |
| 124 | + else: |
| 125 | + raise TypeError(f"Only GBTDAALRegressor can be created from\ |
| 126 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 127 | + # Build GBTDAALRegressor from CatBoost |
| 128 | + elif (submodule_name, class_name) == ("catboost.core", "CatBoostRegressor"): |
| 129 | + if self_class_name == "GBTDAALRegressor": |
| 130 | + self._convert_model_from_catboost(model) |
| 131 | + else: |
| 132 | + raise TypeError(f"Only GBTDAALRegressor can be created from\ |
| 133 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 134 | + # Build GBTDAALModel from LightGBM |
| 135 | + elif (submodule_name, class_name) == ("lightgbm.basic", "Booster"): |
| 136 | + if self_class_name == "GBTDAALModel": |
| 137 | + self._convert_model_from_lightgbm(model) |
| 138 | + else: |
| 139 | + raise TypeError(f"Only GBTDAALModel can be created from\ |
| 140 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 141 | + # Build GBTDAALModel from XGBoost |
| 142 | + elif (submodule_name, class_name) == ("xgboost.core", "Booster"): |
| 143 | + if self_class_name == "GBTDAALModel": |
| 144 | + self._convert_model_from_xgboost(model) |
| 145 | + else: |
| 146 | + raise TypeError(f"Only GBTDAALModel can be created from\ |
| 147 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 148 | + # Build GBTDAALModel from CatBoost |
| 149 | + elif (submodule_name, class_name) == ("catboost.core", "CatBoost"): |
| 150 | + if self_class_name == "GBTDAALModel": |
| 151 | + self._convert_model_from_catboost(model) |
| 152 | + else: |
| 153 | + raise TypeError(f"Only GBTDAALModel can be created from\ |
| 154 | + {submodule_name}.{class_name} (got {self_class_name})") |
| 155 | + else: |
| 156 | + raise TypeError(f"Unknown model format {submodule_name}.{class_name}") |
| 157 | + |
| 158 | + def _predict_classification(self, X, fptype, resultsToEvaluate): |
| 159 | + if X.shape[1] != self.n_features_in_: |
| 160 | + raise ValueError('Shape of input is different from what was seen in `fit`') |
| 161 | + |
| 162 | + if not hasattr(self, 'daal_model_'): |
| 163 | + raise ValueError(( |
| 164 | + "The class {} instance does not have 'daal_model_' attribute set. " |
| 165 | + "Call 'fit' with appropriate arguments before using this method.") |
| 166 | + .format(type(self).__name__)) |
| 167 | + |
| 168 | + # Prediction |
| 169 | + predict_algo = d4p.gbt_classification_prediction( |
| 170 | + fptype=fptype, |
| 171 | + nClasses=self.n_classes_, |
| 172 | + resultsToEvaluate=resultsToEvaluate) |
| 173 | + predict_result = predict_algo.compute(X, self.daal_model_) |
| 174 | + |
| 175 | + if resultsToEvaluate == "computeClassLabels": |
| 176 | + return predict_result.prediction.ravel().astype(np.int64, copy=False) |
| 177 | + else: |
| 178 | + return predict_result.probabilities |
| 179 | + |
| 180 | + def _predict_regression(self, X, fptype): |
| 181 | + if X.shape[1] != self.n_features_in_: |
| 182 | + raise ValueError('Shape of input is different from what was seen in `fit`') |
| 183 | + |
| 184 | + if not hasattr(self, 'daal_model_'): |
| 185 | + raise ValueError(( |
| 186 | + "The class {} instance does not have 'daal_model_' attribute set. " |
| 187 | + "Call 'fit' with appropriate arguments before using this method.").format( |
| 188 | + type(self).__name__)) |
| 189 | + |
| 190 | + # Prediction |
| 191 | + predict_algo = d4p.gbt_regression_prediction(fptype=fptype) |
| 192 | + predict_result = predict_algo.compute(X, self.daal_model_) |
| 193 | + |
| 194 | + return predict_result.prediction.ravel() |
| 195 | + |
| 196 | + |
| 197 | +class GBTDAALModel(GBTDAALBaseModel): |
| 198 | + def __init__(self): |
| 199 | + pass |
| 200 | + |
| 201 | + def predict(self, X): |
| 202 | + fptype = getFPType(X) |
| 203 | + if self._is_regression: |
| 204 | + return self._predict_regression(X, fptype) |
| 205 | + else: |
| 206 | + return self._predict_classification(X, fptype, "computeClassLabels") |
| 207 | + |
| 208 | + def predict_proba(self, X): |
| 209 | + fptype = getFPType(X) |
| 210 | + if self._is_regression: |
| 211 | + raise NotImplementedError("Can't predict probabilities for regression task") |
| 212 | + else: |
| 213 | + return self._predict_classification(X, fptype, "computeClassProbabilities") |
| 214 | + |
| 215 | + |
| 216 | +def convert_model(model): |
| 217 | + gbm = GBTDAALModel() |
| 218 | + gbm._convert_model(model) |
| 219 | + |
| 220 | + gbm._is_regression = isinstance(gbm.daal_model_, d4p.gbt_regression_model) |
| 221 | + |
| 222 | + return gbm |
0 commit comments