1
votes

I am trying to deploy the existing breast cancer prediction model on Amazon Sagemanker using AWS Lambda and API gateway. I have followed the official documentation from the below url.

https://aws.amazon.com/blogs/machine-learning/call-an-amazon-sagemaker-model-endpoint-using-amazon-api-gateway-and-aws-lambda/

I am getting a type error at "predicted_label".

 result = json.loads(response['Body'].read().decode())
 print(result)
 pred = int(result['predictions'][0]['predicted_label'])
 predicted_label = 'M' if pred == 1 else 'B'

 return predicted_label

please let me know if someone could resolve this issue. Thank you.

1

1 Answers

3
votes

By printing the result type by print(type(result)) you can see its a dictionary. now you can see the key name is "score" instead of "predicted_label" that you are giving to pred. Hence replace it with

pred = int(result['predictions'][0]['score'])

I think this solves your problem.

here is my lambda function:

import os
import io
import boto3
import json
import csv

# grab environment variables
ENDPOINT_NAME = os.environ['ENDPOINT_NAME']
runtime= boto3.client('runtime.sagemaker')

def lambda_handler(event, context):
   print("Received event: " + json.dumps(event, indent=2))

   data = json.loads(json.dumps(event))
   payload = data['data']
   print(payload)

   response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
                                      ContentType='text/csv',
                                      Body=payload)
   #print(response)
   print(type(response))
   for key,value in response.items():
       print(key,value)
   result = json.loads(response['Body'].read().decode())
   print(type(result))
   print(result['predictions'])
   pred = int(result['predictions'][0]['score'])
   print(pred)
   predicted_label = 'M' if pred == 1 else 'B'

   return predicted_label