Object of type ndarray is not JSON serializable: API endpoint

Question:

I have a Python script which takes a list as input schema and return a record as output schema like this-

# Initialize the deployment environment
def init():
    #load model from local file here
    

standard_sample_input = StandardPythonParameterType([19.0,168.88745536965698,448.15396972858315,97.63243953079672,39.92323264491041,98.13586382473882])
                                        
sample_input = StandardPythonParameterType({'input1': standard_sample_input})                                        

sample_output = StandardPythonParameterType([16.62585])
outputs = StandardPythonParameterType({'Results':sample_output})                                        

@input_schema('Inputs', sample_input)
@output_schema(outputs)

# Run the model and return the scored result.    
def run(Inputs):
    response = ''
    try:  
        prediction = regressor.predict(Inputs)

    return prediction

Now I am deploying this script and getting a REST Endpoint. But when I am calling this endpoint with the input schema type, I am getting an error that TypeError: Object of type ndarray is not JSON serializable.

What I fail to understand is that there’s no presence of numpy or numpy array anywhere in my code. It is just a list I am passing. I am just passing a JSON as input and converting that JSON into dictionary, picking up only the values and converting it into a dataframe and passing it to the model to predict.

This is the input I am passing to test the endpoint.

{"Inputs":{"input1":[18.0, 170.54412436868537, 457.122701576177, 99.03802220789595, 40.94298920765353, 0.0, 0.0, 4.585221091701897e-13, 434.66205951841266]}}
Asked By: PeakyBlinder

||

Answers:

The values returned from the call to regressor.predict(Inputs) & assigned to the prediction variable are likely to be a numpy.ndarray.

When you return this, your endpoint will attempt to serialize the array, leading to the reported error.

The array can be converted to a list (which is serialisable) by calling .tolist().
ie.

return prediction.tolist()
Answered By: UpstatePedro