Issue while invoking sagemaker endpoints with greyscale images
I am using Sagemaker Image Classification algorithm from following container,
bucket = 'my-s3-bucket'
container = '811284229777.dkr.ecr.us-east-1.amazonaws.com/image-classification:latest'
training_image = container
job_name = 'my_job_1'
My model is trained from scratch with below parameters using content type as application/x-recordio, Notice the image_shape parameter!
num_layers = 18
image_shape = "1,256,256"
num_training_samples = 52940
num_classes = 176
mini_batch_size = 128
epochs = 20
learning_rate = 0.01
top_k = 5
checkpoint_frequency = 1
use_pretrained_model = 0
training_params = \
{
"AlgorithmSpecification": {
"TrainingImage": training_image,
"TrainingInputMode": "File"
},
"RoleArn": role,
"OutputDataConfig": {
"S3OutputPath": 's3://{}/sld/{}/output'.format(bucket, job_name_prefix)
},
"ResourceConfig": {
"InstanceCount": 1,
"InstanceType": "ml.p2.xlarge",
"VolumeSizeInGB": 50
},
"TrainingJobName": job_name,
"HyperParameters": {
"image_shape": image_shape,
"num_layers": str(num_layers),
"num_training_samples": str(num_training_samples),
"num_classes": str(num_classes),
"mini_batch_size": str(mini_batch_size),
"epochs": str(epochs),
"learning_rate": str(learning_rate),
"checkpoint_frequency": str(checkpoint_frequency),
"use_pretrained_model": str(use_pretrained_model)
},
"StoppingCondition": {
"MaxRuntimeInSeconds": 360000
},
"InputDataConfig": [
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": 's3://{}/sld/train/'.format(bucket),
"S3DataDistributionType": "FullyReplicated"
}
},
"ContentType": "application/x-recordio",
"CompressionType": "None"
},
{
"ChannelName": "validation",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": 's3://{}/sld/validation/'.format(bucket),
"S3DataDistributionType": "FullyReplicated"
}
},
"ContentType": "application/x-recordio",
"CompressionType": "None"
}
]
}
Upon trying to invoke with following code,
def runtime_sagemaker(image_path, endpoint_name='some_my_endpoint'):
with open(image_path, 'rb') as f:
payload = f.read()
payload = bytearray(payload)
response = runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType='application/x-image', Body=payload)
I am getting,
---------------------------------------------------------------------------
ModelError Traceback (most recent call last)
<ipython-input-183-93edb2593c1b> in <module>()
----> 1 runtime_sagemaker(df_image_data.loc[0, 'image_path'])
<ipython-input-182-34d14b0560f0> in runtime_sagemaker(image_path, endpoint_name)
3 payload = f.read()
4 payload = bytearray(payload)
----> 5 response = runtime.invoke_endpoint(EndpointName=endpoint_name, ContentType='application/x-image', Body=payload)
D:\milind.dalvi\personal\_python\Anaconda3\lib\site-packages\botocore\client.py in _api_call(self, *args, **kwargs)
322 "%s() only accepts keyword arguments." % py_operation_name)
323 # The "self" in this scope is referring to the BaseClient.
--> 324 return self._make_api_call(operation_name, kwargs)
325
326 _api_call.__name__ = str(py_operation_name)
D:\milind.dalvi\personal\_python\Anaconda3\lib\site-packages\botocore\client.py in _make_api_call(self, operation_name, api_params)
620 error_code = parsed_response.get("Error", {}).get("Code")
621 error_class = self.exceptions.from_code(error_code)
--> 622 raise error_class(parsed_response, operation_name)
623 else:
624 return parsed_response
ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received client error (400) from model with message "unable to evaluate payload provided: /local/p4clients/pkgbuild-DDdq5/workspace/src/Opencv/build/private/src/modules/imgproc/src/color.cpp:11079: error: (-215) scn == 3 || scn == 4 in function cvtColor
I believe the error has to do something with my input image shape, which is greyscaled and not rgb based on following thread,
https://stackoverflow.com/questions/30506126/open-cv-error-215-scn-3-scn-4-in-function-cvtcolor
Thanks for posting this issue @mdalvi. I am running up against the exact same problem. The model trained on greyscale images without a hitch, but the inference code hits the same error you mentioned. Have you had any luck figuring it out so far?
Hi @mdalvi , @topherdan1
Thanks for your help in highlighting the issue with the SageMaker image classification algorithm. It has now been fixed and the algorithm should be able to handle grayscale images. Can you please try the deployment to the endpoint again with the latest image and let us know if you still see issues.
Thanks! Regards, Amazon SageMaker Team
Resolved.
Hi,
I am getting error while invoking endpoint for deepar algorithm
it says that "Call Failed An error occurred (ModelError) when calling the InvokeEndpoint operation: Received client error (400) from model with message \Unable to evaluate payload provided. See https://us-east-1.console.aws.amazon.com/cloudwatch/home?region=us-east-1#logEventViewer:group=/aws/sagemaker/Endpoints/live-deep-ar-v1 in account 761276118745 for more information"
my code looks like below
import boto3 import math import dateutil import json import os #import numpy as np #import sagemaker
grab environment variables
ENDPOINT_NAME = os.environ['ENDPOINT_NAME'] client = boto3.client(service_name='sagemaker-runtime')
def lambda_handler(event, context):
try:
print("Received event: " + json.dumps(event, indent=2))
request = json.loads(json.dumps(event))
transformed_data = [(instance['target']) for instance in request["instances"]]
payload = bytearray(transformed_data)
result = client.invoke_endpoint(EndpointName=ENDPOINT_NAME, Body= payload, ContentType='application/json')
predictions = result['Body'].read()
return {
'statusCode': 200,
'isBase64Encoded':False,
'body': json.dumps(predictions)
}
except Exception as err:
return {
'statusCode': 400,
'isBase64Encoded':False,
'body': 'Call Failed {0}'.format(err)
}
can anyone help me on this.....