0

我有一个服务帐户,我已授予查看者角色,并已下载凭据 json 文件并为其设置正确的环境变量。我正在尝试在这里运行示例:

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', 'v1beta1')
    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']

但是,这给了我一个 403 和错误The user doesn't have the required permission ml.versions.predict on the resource projects/project/models/model/versions/version。我不确定我做错了什么 - 我正在为凭据设置正确的环境变量,根据他们的文档,服务帐户只需要查看者角色即可访问此端点。我做错了什么?

4

2 回答 2

1

tl; dr discovery.build 可能没有使用预期的服务帐户,因为它尝试了许多身份验证选项

我建议明确而不是依赖默认行为,如:在没有 gcloud 的情况下在生产中使用 CloudML 预测 API。此外,如果您致电,您的项目 IAM 设置可能不包括服务帐户:

gcloud --project "$PROJECT" get-iam-policy 

您是否看到具有角色/查看者或更高级别的预期服务帐户?如果没有,您需要授予它权限。它在服务帐户页面中的存在仅意味着您拥有该服务帐户,而不是允许它做任何事情!

于 2017-05-17T18:05:08.390 回答
0

用接下来的步骤解决了同样的问题:

  1. 创建服务帐户(角色项目查看者)
  2. 下载带有凭据的 json 文件
  3. 调用它使用

    from oauth2client.service_account import ServiceAccountCredentials

    from googleapiclient import discovery

    credentials = ServiceAccountCredentials.from_json_keyfile_name('your_creds.json')

    service = discovery.build('ml', 'v1', credentials=credentials)

于 2017-05-31T13:13:32.773 回答