使用 CLI/Python API 导出 Google AutoML 模型

问题描述

GCP AutoML WebUI 无法导出模型用于离线推理已经有几天了(support team 说这是一个前端组件错误,已经修复,已经有几天了,但还没有)。

说到这里,我通常不喜欢 GUI 来做那件事,我希望我可以使用 CLIPython google-cloud-automl API 来完成这项工作。我不得不承认谷歌在文档方面很糟糕,他们不断地改变功能而没有提供细节和例子。尽管各种功能都在工作(存储桶列表、存储桶创建、数据上传到存储桶,甚至模型训练等),但模型导出一直是一个令人头疼且难以配置的问题。在我们继续之前,请注意 GOOGLE_APPLICATION_CREDENTIALS 已添加到环境中。到目前为止我尝试过的:

1.通过 POST:

# get the token
access_token = subprocess.check_output(
    'gcloud auth application-default print-access-token',shell=True)

data = {
  "outputConfig": {
    "modelFormat": "tf_saved_model",#or "tf-saved-model"
    "gcsDestination": {
      "outputUriPrefix": "gs://bucket/folder"
    }
  }
}


headers = {
    'Authorization': f'Bearer {access_token.decode().rstrip()}','Content-Type': 'application/json; charset=utf-8',}

url= f"https://automl.googleapis.com/v1/projects/{project_id}/locations/us-central1/models/{model_id}:export"

response = requests.post(url,headers=headers,json=data)

因 response.content 失败:

b'{\n  "error": {\n    "code": 400,\n    "message": "List of found errors:\\t1.Field: name; Message: required field is invalid\\t",\n    "status": "INVALID_ARGUMENT",\n    "details": [\n      {\n        "@type": "type.googleapis.com/google.rpc.BadRequest",\n        "fieldViolations": [\n          {\n            "field": "name",\n            "description": "required field is invalid"\n          }\n        ]\n      }\n    ]\n  }\n}\n'

2.通过 google-cloud-automl

location = "us-central1"

client = automl.AutoMlClient()
model_full_id = client.model_path(project=project_id,location=location,model=model_id)

response = client.export_model(????)

显然需要参数(如果我运行它 client.export_model()):

1.字段:姓名;消息:未提供位置 ID。
2.字段:名称;消息:必填字段无效
3.字段:output_config.gcs_destination.output_uri_prefix;消息:为 GCS 路径或前缀提供了空字符串。

我一开始就被困在如何传递参数。我试过 通过 automl.types.ModelExportOutputConfig(???) 为 location_to_be_written 和 model_format 配置元数据,但这本身就是一个麻烦。

解决方法

  1. 对于 post 方法,您需要使用 model-id(例如 ICN124...TBL543...
    您可以在 UI => AutoML Models 选项卡上或通过 listing your models 找到您的。
    我已按照您提供的 example 成功导出模型。

  2. 对于库,您需要使用完整路径。
    这是一个工作示例:

from google.cloud import automl

project_id = "YOUR_PROJECT"
model_name="projects/YOUR_PROJECT_NUMBER/locations/us-central1/models/YOUR_MODEL_ID"
gcs_uri = "gs://bucket/folder"

client = automl.AutoMlClient()

gcs_destination = automl.GcsDestination(output_uri_prefix=gcs_uri)
output_config=automl.ModelExportOutputConfig(gcs_destination=gcs_destination,model_format="tflite")

request = automl.ExportModelRequest(name=model_name,output_config=output_config)

response = client.export_model(request=request)

顺便说一句,从 UI 导出的问题现已修复,您应该可以从中导出模型。

,

我提出了同样的问题。我之前经常使用网页来导出模型,我什至能够在上周初导出模型。但是自周五以来无法导出任何离线模型:(无论如何,我尝试了您的第一个 Post 方法,并且使用代码导出模型对我有用。