Invoking the Model

Create a lambda which will invoke the SageMaker endpoint

  • go to the Lambda console
  • create a new lambda function
  • select ‘author from scratch’
  • give a name for your lambda function
  • select python 3.7 runtime
  • make sure your lambda function has permission to invoke sagemaker endpoint (for more details, click here) image
  • click on ‘create function’
  • copy the following Python code to the console: make sure you substitute the end point generated in SageMaker on line 17
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import boto3
import json

print("Loading Lambda Function")

runtime = boto3.client("runtime.sagemaker")


def lambda_handler(event, context):

    # we simulate the data of a new call
    payload = event["payload"]

    # invoking the endpoint: make sure you substitute '<insert-your-endpoint-here>'
    # with your endpoint name for example 'xgboost-2019-03-22-11-38-32-449'
    response = runtime.invoke_endpoint(
        EndpointName="<insert-your-endpoint-here>",
        ContentType="text/csv",
        Body=payload,
    )
    print(response)
    result = json.loads(response["Body"].read().decode())
    print(result)

    predicted_label = {"predicted_label": "Churn" if result > 0.80 else "Not Churn"}
    return predicted_label
  • click on the Save button
  • click on ‘Select a test event’ dropdown, then ‘Configure test events’ option.
    /images/lab1/invoke/selectTestEvent.png
  • tap on ‘Create new test event’, select ‘Hello World’ from the ‘Event template’ dropdown, name your test event ‘churnTest’ and finally copy the following snippet
    {
      "payload": "0,47,28,141.3,94,168.0,108,113.5,84,7.8,2,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0"
    }
  • tap on the ‘Test’ button.

The payload contains the customer sample in a CSV format which we will ‘inject’ into the endpoint .
The expected result from the churn prediction endpoint for this customer sample is Churn.