Skip to content

Commit 614e2f2

Browse files
thedriftofwordsengelke
authored andcommitted
Create scikit-xg-predict.py (#1422)
* Create scikit-xg-predict.py This predict_json method uses exactly the same code as in https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/ml_engine/online_prediction/predict.py#L28. The only difference is that the definition of instances at line 29 is updated to be more appropriate for scikit and xgb. Kathy provided the updated definition. * Lint tweaks * Trailing whitespace removed.
1 parent df2193f commit 614e2f2

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
# Copyright 2018 Google Inc. All Rights Reserved.
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+
"""Examples of using the Cloud ML Engine's online prediction service,
17+
modified for scikit-learn and XGBoost."""
18+
19+
import googleapiclient.discovery
20+
21+
22+
# [START predict_json]
23+
def predict_json(project, model, instances, version=None):
24+
"""Send json data to a deployed model for prediction.
25+
Args:
26+
project (str): project where the Cloud ML Engine Model is deployed.
27+
model (str): model name.
28+
instances ([[float]]): List of input instances, where each input
29+
instance is a list of floats.
30+
version: str, version of the model to target.
31+
Returns:
32+
Mapping[str: any]: dictionary of prediction results defined by the
33+
model.
34+
"""
35+
# Create the ML Engine service object.
36+
# To authenticate set the environment variable
37+
# GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
38+
service = googleapiclient.discovery.build('ml', 'v1')
39+
name = 'projects/{}/models/{}'.format(project, model)
40+
41+
if version is not None:
42+
name += '/versions/{}'.format(version)
43+
44+
response = service.projects().predict(
45+
name=name,
46+
body={'instances': instances}
47+
).execute()
48+
49+
if 'error' in response:
50+
raise RuntimeError(response['error'])
51+
52+
return response['predictions']
53+
# [END predict_json]

0 commit comments

Comments
 (0)