Repository navigation
xgboost/sqlflow_data_source #647
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
sperlingxx
merged 2 commits into
sql-machine-learning:develop
from
sperlingxx:xgboost_dev
Aug 12, 2019
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| # Copyright 2019 The SQLFlow Authors. All rights reserved. | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # Copyright 2019 The SQLFlow Authors. All rights reserved. | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
|
|
||
| class XGBoostError(Exception): | ||
| pass |
211 changes: 211 additions & 0 deletions
211
sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| # Copyright 2019 The SQLFlow Authors. All rights reserved. | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| import json | ||
| import typing | ||
| from typing import Iterator | ||
|
|
||
| from launcher.data_units import RecordBuilder | ||
|
|
||
| from .common import XGBoostError | ||
| from ..db import connect, insert_values, db_generator | ||
| from launcher import DataSource, config_fields, XGBoostResult, XGBoostRecord | ||
|
|
||
|
|
||
| class FeatureMeta(typing.NamedTuple): | ||
| feature_name: str | ||
| dtype: str = 'string' | ||
| delimiter: str = '' | ||
| shape: typing.List[int] = [1] | ||
| is_sparse: bool = False | ||
| fc_code: str = None | ||
|
|
||
| @classmethod | ||
| def convert_shape(cls, value) -> typing.List: | ||
| if isinstance(value, str): | ||
| shape = eval(value) | ||
| assert isinstance(shape, typing.List) | ||
| return shape | ||
| elif isinstance(value, typing.List): | ||
| return value | ||
| else: | ||
| raise XGBoostError('invalid shape %s of FeatureMeta' % value) | ||
|
|
||
|
|
||
| class SqlflowDSConfig(typing.NamedTuple): | ||
| is_train: bool | ||
| standard_select: str | ||
| db_config: typing.Dict | ||
| is_tf_integrated: bool | ||
| # FeatureMetas are useless temporarily, since tf transformation is not supported. | ||
| x: typing.List[typing.Dict] | ||
| label: typing.Dict = None | ||
| group: typing.Dict = None | ||
| weight: typing.Dict = None | ||
| output_table: str = None | ||
| write_batch_size: int = 1024 | ||
|
|
||
|
|
||
| class SqlFlowDataSource(DataSource): | ||
| def __init__(self, rank: int, num_worker: int, | ||
| column_conf: config_fields.ColumnFields, | ||
| source_conf): | ||
| super().__init__(rank, num_worker, column_conf, source_conf) | ||
| if not isinstance(source_conf, SqlflowDSConfig): | ||
| raise XGBoostError("SqlflowDataSource: invalid source conf") | ||
|
|
||
| # TODO: support tf.feature_column transformation | ||
| if source_conf.is_tf_integrated: | ||
| raise XGBoostError('So far, tf transformation is not supported in xgboost job.') | ||
|
|
||
| self._train = source_conf.is_train | ||
| self._rcd_builder = RecordBuilder(column_conf.features) | ||
|
|
||
| # concatenate all column fields in use into `col_names` | ||
| # in training mode, there exists [features, label, group(optional), weight(optional)] | ||
| # in prediction mode, there exists [features, result_columns, additional_columns(optional)] | ||
| spec_temp = {'is_sparse': False, 'shape': [1], 'delimiter': ''} | ||
| metas = {} | ||
| col_names = [] | ||
| for col in column_conf.features.columns: | ||
| col_names.append(col) | ||
| metas[col] = spec_temp | ||
| self._feature_len = len(col_names) | ||
|
|
||
| self._label_offset = -1 | ||
| self._group_offset = -1 | ||
| self._weight_offset = -1 | ||
| self._append_indices = [] | ||
| if self._train: | ||
| # label, group, weight column are training specialized | ||
| if column_conf.label: | ||
| self._label_offset = len(col_names) | ||
| col_names.append(column_conf.label) | ||
| metas[column_conf.label] = spec_temp | ||
|
|
||
| if column_conf.group: | ||
| self._group_offset = len(col_names) | ||
| col_names.append(column_conf.group) | ||
| metas[column_conf.group] = spec_temp | ||
|
|
||
| if column_conf.weight: | ||
| self._weight_offset = len(col_names) | ||
| col_names.append(column_conf.weight) | ||
| metas[column_conf.weight] = spec_temp | ||
| else: | ||
| # append columns are prediction specialized | ||
| for col in column_conf.append_columns: | ||
| if col in metas: | ||
| self._append_indices.append(col_names.index(col)) | ||
| else: | ||
| self._append_indices.append(len(col_names)) | ||
| col_names.append(col) | ||
| metas[col] = spec_temp | ||
|
|
||
| self._result_schema = {'append_columns': column_conf.append_columns or []} | ||
| self._result_schema.update(column_conf.result_columns._asdict()) | ||
|
|
||
| conn = connect(**source_conf.db_config) | ||
|
|
||
| # Since label field has already been included into `col_names`, we just fill `label_column_name` with None. | ||
| self._reader = db_generator( | ||
| driver=source_conf.db_config['driver'], | ||
| conn=conn, | ||
| statement=source_conf.standard_select, | ||
| feature_column_names=col_names, | ||
| label_column_name=None, | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just confusion why the label column is None.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because all column fields in use have already been included in feature_column_names. |
||
| feature_specs=metas) | ||
|
|
||
| self._write_partial = None | ||
| if not self._train: | ||
| if not source_conf.output_table: | ||
| raise XGBoostError('Output_table must be defined in xgboost prediction job.') | ||
|
|
||
| def write_data_partial(table_schema, data): | ||
| insert_values( | ||
| driver=source_conf.db_config['driver'], | ||
| conn=conn, | ||
| table_name=source_conf.output_table, | ||
| table_schema=table_schema, | ||
| values=data) | ||
|
|
||
| self._write_partial = write_data_partial | ||
| self._write_batch_size = source_conf.write_batch_size | ||
| self._write_buffer = [] | ||
|
|
||
| def _read_impl(self): | ||
| label = None | ||
| group = None | ||
| weight = 1.0 | ||
| append_cols = [] | ||
| for columns, _ in self._reader(): | ||
| features = columns[:self._feature_len] | ||
| if self._label_offset >= 0: | ||
| label = columns[self._label_offset] | ||
| if self._group_offset >= 0: | ||
| group = columns[self._group_offset] | ||
| if self._weight_offset >= 0: | ||
| weight = columns[self._weight_offset] | ||
| if self._append_indices: | ||
| append_cols = [columns[i] for i in self._append_indices] | ||
| yield features, label, group, weight, append_cols | ||
|
|
||
| def read(self) -> Iterator[XGBoostRecord]: | ||
| for features, label, group, weight, append_cols in self._read_impl(): | ||
| yield self._rcd_builder.build(features, label, group, weight, append_info=append_cols) | ||
|
|
||
| def write(self, result_iter: Iterator[XGBoostResult]): | ||
| # peek one record for schema inference | ||
| peek_ret = result_iter.__next__() | ||
|
|
||
| # build table_schema | ||
| table_schema = [self._result_schema['result_column']] | ||
| table_schema.extend(self._result_schema['append_columns']) | ||
| output_leaf = False | ||
| if peek_ret.leaf_indices and self._result_schema['leaf_column']: | ||
| output_leaf = True | ||
| table_schema.append(self._result_schema['leaf_column']) | ||
| output_prob = False | ||
| if peek_ret.classification_prob and self._result_schema['probability_column']: | ||
| output_prob = True | ||
| table_schema.append(self._result_schema['probability_column']) | ||
| output_detail = False | ||
| if peek_ret.classification_detail and self._result_schema['detail_column']: | ||
| output_detail = True | ||
| table_schema.append(self._result_schema['detail_column']) | ||
|
|
||
| def append_row(xgb_ret: XGBoostResult): | ||
| row = [xgb_ret.result] | ||
| if xgb_ret.append_info: | ||
| row.extend(xgb_ret.append_info) | ||
| if output_leaf: | ||
| row.append(','.join(map(str, xgb_ret.leaf_indices))) | ||
| if output_prob: | ||
| row.append(xgb_ret.classification_prob) | ||
| if output_detail: | ||
| detail = {i: p for i, p in enumerate(xgb_ret.classification_detail)} | ||
| row.append(json.dumps(detail)) | ||
| self._write_buffer.append(row) | ||
|
|
||
| # append the peek record | ||
| append_row(peek_ret) | ||
|
|
||
| # batching write with a buffer | ||
| for ret in result_iter: | ||
| append_row(ret) | ||
| if len(self._write_buffer) >= self._write_batch_size: | ||
| self._write_partial(table_schema, self._write_buffer) | ||
| self._write_buffer = [] | ||
|
|
||
| # clean the buffer | ||
| if self._write_buffer: | ||
| self._write_partial(table_schema, self._write_buffer) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
SqlflowDSConfigcan be capital toSQLFlowDSConfig.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done