我有一个非常简单的 CNN 模型,一个多标签图像分类器,我在 Colab 笔记本中进行了预训练。我保存了模型和权重,并将其作为模型上传到 Google Cloud AI Platform(统一)中。
我正在使用 Cloud Functions 从 URL 下载图像并使用 Google 的aiplatform
Python 库将其传递给分类器。
分类器的输入层采用[1, 180, 180, 3]
(具有 3 个通道的 180x180 图像)的形状。
我用来将其发送到我的模型的代码基于Google 的官方示例。
我的问题是:instances
下面的代码需要是什么样的?我是否需要以某种方式将其解析为 JSON 或其他格式?我只是不明白这个对象应该是什么才能把它放到我的模型中。
此代码使用 Google 的aiplatform
Python 库。
# Code used to download and transform the image to a shape of [1, 180, 180, 3]
def load_image(url):
response = requests.get(url)
img_bytes = BytesIO(response.content)
img = Image.open(img_bytes)
img = img.convert('RGB')
img = img.resize((180,180), Image.NEAREST)
arr = preprocessing.image.img_to_array(img)
arr = tf.expand_dims(arr, 0)
return arr
发送预测:
if request_json['url']:
url = request_json['url']
image_array = load_image(url)
client_options = {"api_endpoint": API_ENDPOINT}
client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)
我不明白示例中接下来的两行中发生了什么。 我的模型需要了解 image_bytes 吗?我应该向它发送base64吗?
instance_dict = {"image_bytes": {"b64": image_array}, "key": "0"}
instance = json_format.ParseDict(instance_dict, Value())
instances=[image_array]
parameters_dict = {}
parameters = json_format.ParseDict(parameters_dict, Value())
endpoint = client.endpoint_path(
project=PROJECT_ID, location=LOCATION, endpoint=ENDPOINT_ID
)
response = client.predict(
endpoint=endpoint, instances=instances, parameters=parameters
)
print("response")
print(" deployed_model_id:", response.deployed_model_id)
# The predictions are a google.protobuf.Value representation of the model's predictions.
predictions = response.predictions
for prediction in predictions:
print(" prediction:", dict(prediction))
return predictions
当我点击我的云函数时,它会下载它并将其转换为该形状,但随后我收到此错误消息和堆栈跟踪(图像具有白色背景,因此 [255, 255, 255] 是正确的):
File "/env/local/lib/python3.7/site-packages/google/cloud/aiplatform_v1/services/prediction_service/client.py", line 436, in predict
request.instances.extend(instances)
File "/env/lib/python3.7/_collections_abc.py", line 990, in extend
self.append(v)
File "/env/lib/python3.7/_collections_abc.py", line 971, in append
self.insert(len(self), value)
File "/env/local/lib/python3.7/site-packages/proto/marshal/collections/repeated.py", line 177, in insert
pb_value = self._marshal.to_proto(self._pb_type, value)
File "/env/local/lib/python3.7/site-packages/proto/marshal/marshal.py", line 208, in to_proto
pb_value = rule.to_proto(value)
File "/env/local/lib/python3.7/site-packages/google/cloud/aiplatform/helpers/_decorators.py", line 33, in to_proto
return super().to_proto(value)
File "/env/local/lib/python3.7/site-packages/proto/marshal/rules/struct.py", line 80, in to_proto
raise ValueError("Unable to coerce value: %r" % value)
**ValueError: Unable to coerce value:** <tf.Tensor: shape=(1, 180, 180, 3), dtype=float32, numpy=
array([[[[255., 255., 255.],
[255., 255., 255.],
[255., 255., 255.],
...,
**snip**
...,
[255., 255., 255.],
[255., 255., 255.],
[255., 255., 255.]]]], dtype=float32)>
我应该如何格式化对模型的实际调用?