|
| 1 | +# Copyright 2020 The SQLFlow Authors. All rights reserved. |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | + |
| 14 | +import os |
| 15 | + |
| 16 | +import numpy as np |
| 17 | +import runtime.temp_file as temp_file |
| 18 | +import runtime.xgboost as xgboost_extended |
| 19 | +import sklearn.metrics |
| 20 | +import xgboost as xgb |
| 21 | +from runtime import db |
| 22 | +from runtime.feature.compile import compile_ir_feature_columns |
| 23 | +from runtime.feature.derivation import get_ordered_field_descs |
| 24 | +from runtime.feature.field_desc import DataType |
| 25 | +from runtime.local.xgboost_submitter.predict import _calc_predict_result |
| 26 | +from runtime.model.model import Model |
| 27 | +from runtime.xgboost.dataset import xgb_dataset |
| 28 | + |
| 29 | +SKLEARN_METRICS = [ |
| 30 | + 'accuracy_score', |
| 31 | + 'average_precision_score', |
| 32 | + 'balanced_accuracy_score', |
| 33 | + 'brier_score_loss', |
| 34 | + 'cohen_kappa_score', |
| 35 | + 'explained_variance_score', |
| 36 | + 'f1_score', |
| 37 | + 'fbeta_score', |
| 38 | + 'hamming_loss', |
| 39 | + 'hinge_loss', |
| 40 | + 'log_loss', |
| 41 | + 'mean_absolute_error', |
| 42 | + 'mean_squared_error', |
| 43 | + 'mean_squared_log_error', |
| 44 | + 'median_absolute_error', |
| 45 | + 'precision_score', |
| 46 | + 'r2_score', |
| 47 | + 'recall_score', |
| 48 | + 'roc_auc_score', |
| 49 | + 'zero_one_loss', |
| 50 | +] |
| 51 | + |
| 52 | + |
| 53 | +def evaluate(datasource, |
| 54 | + select, |
| 55 | + result_table, |
| 56 | + load, |
| 57 | + pred_label_name=None, |
| 58 | + validation_metrics=["accuracy_score"]): |
| 59 | + """ |
| 60 | + Do evaluation to a trained XGBoost model. |
| 61 | +
|
| 62 | + Args: |
| 63 | + datasource (str): the database connection string. |
| 64 | + select (str): the input data to predict. |
| 65 | + result_table (str): the output data table. |
| 66 | + load (str): where the trained model stores. |
| 67 | + pred_label_name (str): the label column name. |
| 68 | + validation_metrics (list[str]): the evaluation metric names. |
| 69 | +
|
| 70 | + Returns: |
| 71 | + None. |
| 72 | + """ |
| 73 | + model = Model.load_from_db(datasource, load) |
| 74 | + model_params = model.get_meta("attributes") |
| 75 | + train_fc_map = model.get_meta("features") |
| 76 | + train_label_desc = model.get_meta("label").get_field_desc()[0] |
| 77 | + if pred_label_name: |
| 78 | + train_label_desc.name = pred_label_name |
| 79 | + |
| 80 | + field_descs = get_ordered_field_descs(train_fc_map) |
| 81 | + feature_column_names = [fd.name for fd in field_descs] |
| 82 | + feature_metas = dict([(fd.name, fd.to_dict()) for fd in field_descs]) |
| 83 | + |
| 84 | + # NOTE: in the current implementation, we are generating a transform_fn |
| 85 | + # from the COLUMN clause. The transform_fn is executed during the process |
| 86 | + # of dumping the original data into DMatrix SVM file. |
| 87 | + compiled_fc = compile_ir_feature_columns(train_fc_map, model.get_type()) |
| 88 | + transform_fn = xgboost_extended.feature_column.ComposedColumnTransformer( |
| 89 | + feature_column_names, *compiled_fc["feature_columns"]) |
| 90 | + |
| 91 | + bst = xgb.Booster() |
| 92 | + bst.load_model("my_model") |
| 93 | + conn = db.connect_with_data_source(datasource) |
| 94 | + |
| 95 | + result_column_names = _create_evaluate_table(conn, result_table, |
| 96 | + validation_metrics) |
| 97 | + |
| 98 | + with temp_file.TemporaryDirectory() as tmp_dir_name: |
| 99 | + pred_fn = os.path.join(tmp_dir_name, "predict.txt") |
| 100 | + |
| 101 | + dpred = xgb_dataset(datasource=datasource, |
| 102 | + fn=pred_fn, |
| 103 | + dataset_sql=select, |
| 104 | + feature_metas=feature_metas, |
| 105 | + feature_column_names=feature_column_names, |
| 106 | + label_meta=train_label_desc.to_dict(), |
| 107 | + cache=True, |
| 108 | + batch_size=10000, |
| 109 | + transform_fn=transform_fn) |
| 110 | + |
| 111 | + for i, pred_dmatrix in enumerate(dpred): |
| 112 | + feature_file_name = pred_fn + "_%d" % i |
| 113 | + preds = _calc_predict_result(bst, pred_dmatrix, model_params) |
| 114 | + _store_evaluate_result(preds, feature_file_name, train_label_desc, |
| 115 | + result_table, result_column_names, |
| 116 | + validation_metrics, conn) |
| 117 | + |
| 118 | + conn.close() |
| 119 | + |
| 120 | + |
| 121 | +def _create_evaluate_table(conn, result_table, validation_metrics): |
| 122 | + """ |
| 123 | + Create the result table to store the evaluation result. |
| 124 | +
|
| 125 | + Args: |
| 126 | + conn: the database connection object. |
| 127 | + result_table (str): the output data table. |
| 128 | + validation_metrics (list[str]): the evaluation metric names. |
| 129 | +
|
| 130 | + Returns: |
| 131 | + The column names of the created table. |
| 132 | + """ |
| 133 | + result_columns = ['loss'] + validation_metrics |
| 134 | + float_field_type = DataType.to_db_field_type(conn.driver, DataType.FLOAT32) |
| 135 | + column_strs = [ |
| 136 | + "%s %s" % (name, float_field_type) for name in result_columns |
| 137 | + ] |
| 138 | + |
| 139 | + drop_sql = "DROP TABLE IF EXISTS %s;" % result_table |
| 140 | + create_sql = "CREATE TABLE %s (%s);" % (result_table, |
| 141 | + ",".join(column_strs)) |
| 142 | + conn.execute(drop_sql) |
| 143 | + conn.execute(create_sql) |
| 144 | + |
| 145 | + return result_columns |
| 146 | + |
| 147 | + |
| 148 | +def _store_evaluate_result(preds, feature_file_name, label_desc, result_table, |
| 149 | + result_column_names, validation_metrics, conn): |
| 150 | + """ |
| 151 | + Save the evaluation result in the table. |
| 152 | +
|
| 153 | + Args: |
| 154 | + preds: the prediction result. |
| 155 | + feature_file_name (str): the file path where the feature dumps. |
| 156 | + label_desc (FieldDesc): the label FieldDesc object. |
| 157 | + result_table (str): the result table name. |
| 158 | + result_column_names (list[str]): the result column names. |
| 159 | + validation_metrics (list[str]): the evaluation metric names. |
| 160 | + conn: the database connection object. |
| 161 | +
|
| 162 | + Returns: |
| 163 | + None. |
| 164 | + """ |
| 165 | + y_test = [] |
| 166 | + with open(feature_file_name, 'r') as f: |
| 167 | + for line in f.readlines(): |
| 168 | + row = [i for i in line.strip().split("\t")] |
| 169 | + # DMatrix store label in the first column |
| 170 | + if label_desc.dtype == DataType.INT64: |
| 171 | + y_test.append(int(row[0])) |
| 172 | + elif label_desc.dtype == DataType.FLOAT32: |
| 173 | + y_test.append(float(row[0])) |
| 174 | + else: |
| 175 | + raise TypeError("unsupported data type {}".format( |
| 176 | + label_desc.dtype)) |
| 177 | + |
| 178 | + y_test = np.array(y_test) |
| 179 | + |
| 180 | + evaluate_results = dict() |
| 181 | + for metric_name in validation_metrics: |
| 182 | + metric_name = metric_name.strip() |
| 183 | + if metric_name not in SKLEARN_METRICS: |
| 184 | + raise ValueError("unsupported metrics %s" % metric_name) |
| 185 | + metric_func = getattr(sklearn.metrics, metric_name) |
| 186 | + metric_value = metric_func(y_test, preds) |
| 187 | + evaluate_results[metric_name] = metric_value |
| 188 | + |
| 189 | + # write evaluation result to result table |
| 190 | + with db.buffered_db_writer(conn, result_table, result_column_names) as w: |
| 191 | + row = ["0.0"] |
| 192 | + for mn in validation_metrics: |
| 193 | + row.append(str(evaluate_results[mn])) |
| 194 | + w.write(row) |
0 commit comments