我能够成功将批量图像作为 numpy 数组发送到使用 TF 服务设置的 SageMaker 端点并获得响应,如下所示:
def predict_random_batch(self, batch_size, verbose=0, initial_args=None):
batch = np.random.uniform(low=-1.0, high=1.0, size=(batch_size,self.size,self.size,3))
data = {'instances': np.asarray(batch).astype(self.dtype)}
if verbose: self.total_size(data)
request_args = self._create_request_args(data, initial_args)
response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
probs = self._handle_response(response)['predictions']
return probs
predictor.predict_random_batch(3)
但是,numpy 数组非常大。我正在尝试在发送之前压缩图像批处理。这就是我正在尝试的:
def predict_random_batch_TEST(self, batch_size, verbose=0, initial_args=None):
import base64
batch = np.random.uniform(low=-1.0, high=1.0, size=(batch_size,self.size,self.size,3))
batch = batch.astype(self.dtype)
encoded_input_string = base64.b64encode(batch)
input_string = encoded_input_string.decode("utf-8")
instance = [{"b64": input_string}]
data = json.dumps({"instances": instance})
request_args = self._create_request_args(data, initial_args)
if verbose: self.total_size(data)
response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
probs = self._handle_response(response)['predictions']
return probs
但是这会返回错误:
ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received client error (400) from model with message "{ "error": "JSON Value: . . . Is not object" }"
有人知道如何压缩一批图像以便能够发送更大的批量大小吗?显然 SM 施加了 5MB 的有效负载限制,当作为 numpy 数组发送时,这个限制并不是很大。
最佳答案
在将图像发送到端点之前,我使用单独的 API 来调整图像大小。这是代码片段,您调整它应该没有问题。
h = body['height']
w = body['width']
image = base64.b64decode(body['data'])
L = len(image)
image = np.fromstring(image, np.uint8)
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
(H, W, _) = image.shape
image = cv2.resize(image, (h, w,))
image = cv2.imencode('.jpeg', image)
data = base64.b64encode(image[1].tostring())
完整帖子:https://medium.com/@julsimon/using-chalice-to-serve-sagemaker-predictions-a2015c02b033
关于python-3.x - 在发送到 SageMaker TF Serving 之前压缩图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54269635/