gcloud ml-engine API

gcloud ml-engine API

python 的 google-cloud 客户端库中是否包含 gcloud ml-engine 调用?我目前找不到它的任何文档(尽管我看到了自然语言 API)。我正在尝试通过 API 在 jupyter notebook 中复制以下命令,但没有成功:

gcloud ml-engine local predict --json-instances=XXX --model-dir=YYY

更新 解决方案

with open('test.json') as data_file:    
    json_request = json.load(data_file)

response = predict_json(project = PROJECT_ID,
                        model= 'test_model',
                        instances = [json_request],
                        version = 'v1')

我相信您要查找的内容可以在 "Requesting predictions" 部分下的 official documentation 中找到(请务必单击 Python 选项卡)。

为了您的方便:

def predict_json(project, model, instances, version=None):
    """Send json data to a deployed model for prediction.

    Args:
        project (str): project where the Cloud ML Engine Model is deployed.
        model (str): model name.
        instances ([Mapping[str: Any]]): Keys should be the names of Tensors
            your deployed model expects as inputs. Values should be datatypes
            convertible to Tensors, or (potentially nested) lists of datatypes
            convertible to tensors.
        version: str, version of the model to target.
    Returns:
        Mapping[str: any]: dictionary of prediction results defined by the
            model.
    """
    # Create the ML Engine service object.
    # To authenticate set the environment variable
    # GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
    service = googleapiclient.discovery.build('ml', 'v1')
    name = 'projects/{}/models/{}'.format(project, model)

    if version is not None:
        name += '/versions/{}'.format(version)

    response = service.projects().predict(
        name=name,
        body={'instances': instances}
    ).execute()

    if 'error' in response:
        raise RuntimeError(response['error'])

    return response['predictions']