|
| 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 | +import tempfile |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +import runtime.xgboost as xgboost_extended |
| 19 | +import xgboost as xgb |
| 20 | +from runtime import db |
| 21 | +from runtime.feature.compile import compile_ir_feature_columns |
| 22 | +from runtime.feature.derivation import get_ordered_field_descs |
| 23 | +from runtime.feature.field_desc import DataType |
| 24 | +from runtime.model.model import Model |
| 25 | +from runtime.xgboost.dataset import xgb_dataset |
| 26 | + |
| 27 | + |
| 28 | +def pred(datasource, select, result_table, pred_label_name, load): |
| 29 | + """ |
| 30 | + Do prediction using a trained model. |
| 31 | +
|
| 32 | + Args: |
| 33 | + datasource (str): the database connection string. |
| 34 | + select (str): the input data to predict. |
| 35 | + result_table (str): the output data table. |
| 36 | + pred_label_name (str): the output label name to predict. |
| 37 | + load (str): where the trained model stores. |
| 38 | +
|
| 39 | + Returns: |
| 40 | + None. |
| 41 | + """ |
| 42 | + model = Model.load_from_db(datasource, load) |
| 43 | + model_params = model.get_meta("attributes") |
| 44 | + train_fc_map = model.get_meta("features") |
| 45 | + train_label_desc = model.get_meta("label").get_field_desc()[0] |
| 46 | + |
| 47 | + field_descs = get_ordered_field_descs(train_fc_map) |
| 48 | + feature_column_names = [fd.name for fd in field_descs] |
| 49 | + feature_metas = dict([(fd.name, fd.to_dict()) for fd in field_descs]) |
| 50 | + |
| 51 | + # NOTE: in the current implementation, we are generating a transform_fn |
| 52 | + # from the COLUMN clause. The transform_fn is executed during the process |
| 53 | + # of dumping the original data into DMatrix SVM file. |
| 54 | + compiled_fc = compile_ir_feature_columns(train_fc_map, model.get_type()) |
| 55 | + transform_fn = xgboost_extended.feature_column.ComposedColumnTransformer( |
| 56 | + feature_column_names, *compiled_fc["feature_columns"]) |
| 57 | + |
| 58 | + bst = xgb.Booster() |
| 59 | + bst.load_model("my_model") |
| 60 | + |
| 61 | + conn = db.connect_with_data_source(datasource) |
| 62 | + result_column_names, train_label_idx = _create_predict_table( |
| 63 | + conn, select, result_table, train_label_desc, pred_label_name) |
| 64 | + |
| 65 | + with tempfile.TemporaryDirectory() as tmp_dir_name: |
| 66 | + pred_fn = os.path.join(tmp_dir_name, "predict.txt") |
| 67 | + raw_data_dir = os.path.join(tmp_dir_name, "predict_raw_dir") |
| 68 | + |
| 69 | + dpred = xgb_dataset( |
| 70 | + datasource=datasource, |
| 71 | + fn=pred_fn, |
| 72 | + dataset_sql=select, |
| 73 | + feature_metas=feature_metas, |
| 74 | + feature_column_names=feature_column_names, |
| 75 | + label_meta=None, |
| 76 | + cache=True, |
| 77 | + batch_size=10000, |
| 78 | + transform_fn=transform_fn, |
| 79 | + raw_data_dir=raw_data_dir) # NOTE: default to use external memory |
| 80 | + |
| 81 | + print("Start predicting XGBoost model...") |
| 82 | + for idx, pred_dmatrix in enumerate(dpred): |
| 83 | + feature_file_name = os.path.join( |
| 84 | + tmp_dir_name, "predict_raw_dir/predict.txt_%d" % idx) |
| 85 | + _predict_and_store_result(bst, pred_dmatrix, model_params, |
| 86 | + result_table, result_column_names, |
| 87 | + train_label_idx, feature_file_name, conn) |
| 88 | + print("Done predicting. Predict table : %s" % result_table) |
| 89 | + |
| 90 | + conn.close() |
| 91 | + |
| 92 | + |
| 93 | +def _predict_and_store_result(bst, dpred, model_params, result_table, |
| 94 | + result_column_names, train_label_idx, |
| 95 | + feature_file_name, conn): |
| 96 | + """ |
| 97 | + Do prediction and save the prediction result in the table. |
| 98 | +
|
| 99 | + Args: |
| 100 | + bst: the XGBoost booster object. |
| 101 | + dpred: the XGBoost DMatrix input data to predict. |
| 102 | + model_params (dict): the XGBoost model parameters. |
| 103 | + result_table (str): the result table name. |
| 104 | + result_column_names (list[str]): the result column names. |
| 105 | + train_label_idx (int): the index where the trained label is inside |
| 106 | + result_column_names. |
| 107 | + feature_file_name (str): the file path where the feature dumps. |
| 108 | + conn: the database connection object. |
| 109 | +
|
| 110 | + Returns: |
| 111 | + None. |
| 112 | + """ |
| 113 | + preds = bst.predict(dpred) |
| 114 | + |
| 115 | + # TODO(yancey1989): should save train_params and model_params |
| 116 | + # not only on PAI submitter |
| 117 | + # TODO(yancey1989): output the original result for various |
| 118 | + # objective function. |
| 119 | + objective = model_params.get("objective", "") |
| 120 | + if objective.startswith("binary:"): |
| 121 | + preds = (preds > 0.5).astype(np.int64) |
| 122 | + elif objective.startswith("multi:") and len(preds) == 2: |
| 123 | + preds = np.argmax(np.array(preds), axis=1) |
| 124 | + |
| 125 | + with db.buffered_db_writer(conn, result_table, result_column_names, |
| 126 | + 100) as w: |
| 127 | + with open(feature_file_name, "r") as feature_file_read: |
| 128 | + line_no = 0 |
| 129 | + for line in feature_file_read.readlines(): |
| 130 | + if not line: |
| 131 | + break |
| 132 | + |
| 133 | + row = [ |
| 134 | + item for i, item in enumerate(line.strip().split("/")) |
| 135 | + if i != train_label_idx |
| 136 | + ] |
| 137 | + row.append(str(preds[line_no])) |
| 138 | + w.write(row) |
| 139 | + line_no += 1 |
| 140 | + |
| 141 | + |
| 142 | +def _create_predict_table(conn, select, result_table, train_label_desc, |
| 143 | + pred_label_name): |
| 144 | + """ |
| 145 | + Create the result prediction table. |
| 146 | +
|
| 147 | + Args: |
| 148 | + conn: the database connection object. |
| 149 | + select (str): the input data to predict. |
| 150 | + result_table (str): the output data table. |
| 151 | + train_label_desc (FieldDesc): the FieldDesc of the trained label. |
| 152 | + pred_label_name (str): the output label name to predict. |
| 153 | +
|
| 154 | + Returns: |
| 155 | + A tuple of (result_column_names, train_label_index). |
| 156 | + """ |
| 157 | + name_and_types = db.selected_columns_and_types(conn, select) |
| 158 | + train_label_index = -1 |
| 159 | + for i, (name, _) in enumerate(name_and_types): |
| 160 | + if name == train_label_desc.name: |
| 161 | + train_label_index = i |
| 162 | + break |
| 163 | + |
| 164 | + if train_label_index >= 0: |
| 165 | + del name_and_types[train_label_index] |
| 166 | + |
| 167 | + column_strs = [] |
| 168 | + for name, typ in name_and_types: |
| 169 | + column_strs.append("%s %s" % |
| 170 | + (name, db.to_db_field_type(conn.driver, typ))) |
| 171 | + |
| 172 | + train_label_field_type = DataType.to_db_field_type(conn.driver, |
| 173 | + train_label_desc.dtype) |
| 174 | + column_strs.append("%s %s" % (pred_label_name, train_label_field_type)) |
| 175 | + |
| 176 | + drop_sql = "DROP TABLE IF EXISTS %s;" % result_table |
| 177 | + create_sql = "CREATE TABLE %s (%s);" % (result_table, |
| 178 | + ",".join(column_strs)) |
| 179 | + conn.execute(drop_sql) |
| 180 | + conn.execute(create_sql) |
| 181 | + result_column_names = [item[0] for item in name_and_types] |
| 182 | + result_column_names.append(pred_label_name) |
| 183 | + return result_column_names, train_label_index |
0 commit comments