Vincent Claes
Vincent Claes

Reputation: 4768

How to construct a "text/csv" payload when invoking a sagemaker endpoint

My training data looks like

df = pd.DataFrame({'A' : [2, 5], 'B' : [1, 7]})

I have trained a model in AWS Sagemaker and I deployed the model behind an endpoint. The endpoint accepts the payload as "text/csv".

to invoke the endpoint using boto3 you can do:

import boto3
client = boto3.client('sagemaker-runtime')
response = client.invoke_endpoint(
    EndpointName="my-sagemaker-endpoint-name",
    Body= my_payload_as_csv,
    ContentType = 'text/csv')

How do i construct the payload "my_payload_as_csv" from my Dataframe in order to invoke the Sagemaker Endpoint correctly?

Upvotes: 5

Views: 5430

Answers (2)

Naveen Reddy Marthala
Naveen Reddy Marthala

Reputation: 3123

@VincentCleas's answer was good. But, If you want to construct csv-payload without installing pandas, do this:

import boto3

csv_buffer = open('<file-name>.csv')
my_payload_as_csv = csv_buffer.read()

client = boto3.client('sagemaker-runtime')
response = client.invoke_endpoint(
    EndpointName="my-sagemaker-endpoint-name",
    Body= my_payload_as_csv,
    ContentType = 'text/csv')

Upvotes: 2

Vincent Claes
Vincent Claes

Reputation: 4768

if you start from the dataframe example

df = pd.DataFrame({'A' : [2, 5], 'B' : [1, 7]})

you take a row

df_1_record = df[:1]

and convert df_1_record to a csv like this:

import io
from io import StringIO
csv_file = io.StringIO()
# by default sagemaker expects comma seperated
df_1_record.to_csv(csv_file, sep=",", header=False, index=False)
my_payload_as_csv = csv_file.getvalue()

my_payload_as_csv looks like

'2,1\n'

then you can invoke the sagemaker endpoint

import boto3
client = boto3.client('sagemaker-runtime')
response = client.invoke_endpoint(
    EndpointName="my-sagemaker-endpoint-name",
    Body= my_payload_as_csv,
    ContentType = 'text/csv')

Upvotes: 8

Related Questions