-
Notifications
You must be signed in to change notification settings - Fork 706
Xgboost predict #789
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
Yancey0623
merged 6 commits into
sql-machine-learning:develop
from
typhoonzero:xgboost_predict
Sep 6, 2019
Merged
Xgboost predict #789
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e167c1a
xgboost predict
typhoonzero 3e04ae4
refine
typhoonzero b0e78d9
update
typhoonzero 76f8dd7
add executor test
typhoonzero 03c3cdc
Merge branch 'develop' of https://github.com/sql-machine-learning/sql…
typhoonzero cb357d7
fix test by merge
typhoonzero 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
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 |
---|---|---|
|
@@ -34,7 +34,7 @@ num_boost_round = {{.NumBoostRound}} | |
maximize = True if "{{.Maximize}}" == "true" else False | ||
early_stopping_rounds = {{.EarlyStoppingRounds}} | ||
if early_stopping_rounds == -1: | ||
early_stopping_rounds = None | ||
early_stopping_rounds = None | ||
|
||
{{if ne .ParamsCfgJSON ""}} | ||
params = {{.ParamsCfgJSON}} | ||
|
@@ -58,22 +58,20 @@ feature_specs["{{$value.FeatureName}}"] = { | |
} | ||
{{end}} | ||
|
||
|
||
|
||
conn = connect(driver, database, user="{{.User}}", password="{{.Password}}", host="{{.Host}}", port={{.Port}}, auth="{{.Auth}}") | ||
|
||
def xgb_dataset(fn, dataset_sql): | ||
gen = db_generator(driver, conn, session_cfg, dataset_sql, feature_column_names, "{{.Y.FeatureName}}", feature_specs) | ||
with open(fn, 'w') as f: | ||
for item in gen(): | ||
features, label = item | ||
row_data = [str(label[0])] + ["%d:%f" % (i, v) for i, v in enumerate(features)] | ||
f.write("\t".join(row_data) + "\n") | ||
# TODO(yancey1989): genearte group and weight text file if necessary | ||
return xgb.DMatrix(fn) | ||
|
||
dtrain = xgb_dataset('train.txt', "{{.TrainingDatasetSQL}}") | ||
dtest = xgb_dataset('test.txt', "{{.ValidationDatasetSQL}}") | ||
gen = db_generator(driver, conn, session_cfg, dataset_sql, feature_column_names, "{{.Y.FeatureName}}", feature_specs) | ||
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. Thanks for fixing the indent. |
||
with open(fn, 'w') as f: | ||
for item in gen(): | ||
features, label = item | ||
row_data = [str(label[0])] + ["%d:%f" % (i, v) for i, v in enumerate(features)] | ||
f.write("\t".join(row_data) + "\n") | ||
# TODO(yancey1989): genearte group and weight text file if necessary | ||
return xgb.DMatrix(fn) | ||
|
||
dtrain = xgb_dataset('train.txt', """{{.TrainingDatasetSQL}}""") | ||
dtest = xgb_dataset('test.txt', """{{.ValidationDatasetSQL}}""") | ||
|
||
train_args = {} | ||
train_args["num_boost_round"] = num_boost_round | ||
|
@@ -84,3 +82,74 @@ train_args["evals"] = [(dtrain, "train"), (dtest, "validation")] | |
bst = xgb.train(params, dtrain, **train_args) | ||
bst.save_model("{{.Save}}") | ||
` | ||
|
||
const xgbPredictTemplateText = ` | ||
import xgboost as xgb | ||
import numpy as np | ||
from sqlflow_submitter.db import connect, db_generator, buffered_db_writer | ||
|
||
driver="{{.Driver}}" | ||
|
||
{{if ne .Database ""}} | ||
database="{{.Database}}" | ||
{{else}} | ||
database="" | ||
{{end}} | ||
|
||
session_cfg = {} | ||
{{ range $k, $v := .Session }} | ||
session_cfg["{{$k}}"] = "{{$v}}" | ||
{{end}} | ||
|
||
feature_column_names = [{{range .X}} | ||
"{{.FeatureName}}", | ||
{{end}}] | ||
|
||
{{/* Convert go side featureSpec to python dict for input_fn */}} | ||
feature_specs = dict() | ||
{{ range $value := .X }} | ||
feature_specs["{{$value.FeatureName}}"] = { | ||
"feature_name": "{{$value.FeatureName}}", | ||
"dtype": "{{$value.Dtype}}", | ||
"delimiter": "{{$value.Delimiter}}", | ||
"shape": {{$value.InputShape}}, | ||
"is_sparse": "{{$value.IsSparse}}" == "true" | ||
} | ||
{{end}} | ||
|
||
conn = connect(driver, database, user="{{.User}}", password="{{.Password}}", host="{{.Host}}", port={{.Port}}, auth="{{.Auth}}") | ||
|
||
def xgb_dataset(fn, dataset_sql): | ||
gen = db_generator(driver, conn, session_cfg, dataset_sql, feature_column_names, "", feature_specs) | ||
with open(fn, 'w') as f: | ||
for item in gen(): | ||
features, label = item | ||
row_data = [str(label[0])] + ["%d:%f" % (i, v) for i, v in enumerate(features)] | ||
f.write("\t".join(row_data) + "\n") | ||
# TODO(yancey1989): genearte group and weight text file if necessary | ||
return xgb.DMatrix(fn) | ||
|
||
dpred = xgb_dataset('predict.txt', """{{.PredictionDatasetSQL}}""") | ||
|
||
bst = xgb.Booster({'nthread': 4}) # init model | ||
bst.load_model("{{.Save}}") # load data | ||
preds = bst.predict(dpred) | ||
# TODO(typhoonzero): regression models may have different behavior | ||
pred_classes = np.argmax(np.array(preds), axis=1) | ||
|
||
feature_file_read = open("predict.txt", "r") | ||
|
||
result_column_names = feature_column_names | ||
result_column_names.append("{{.Y.FeatureName}}") | ||
|
||
line_no = 0 | ||
with buffered_db_writer(driver, conn, "{{.TableName}}", result_column_names, 100) as w: | ||
while True: | ||
line = feature_file_read.readline() | ||
if not line: | ||
break | ||
row = [i.split(":")[1] for i in line.replace("\n", "").split("\t")[1:]] | ||
row.append(pred_classes[line_no]) | ||
w.write(row) | ||
line_no += 1 | ||
` |
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.
Uh oh!
There was an error while loading. Please reload this page.