|
| 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