Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of type 'ndarray' is not JSON serializable

I am new to python and machine learning. I have a Linear Regression model which is able to predict output based on the input which I have dumped to be used with a web service. See the code below:

      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

        regression_model = LinearRegression()
        regression_model.fit(X_train, y_train)
    print(regression_model.predict(np.array([[21, 0, 0, 0, 1, 0, 0, 1, 1, 1]]))) # this is returning my expected output

joblib.dump(regression_model, '../trainedModels/MyTrainedModel.pkl')

Using flask I am trying this to expose as a web service as below:

 @app.route('/predict', methods=['POST'])
def predict():


    X = [[21, 0, 0, 0, 1, 0, 0, 1, 1, 1]]
    model = joblib.load('../trainedModels/MyTrainedModel.pkl')
    prediction = model.predict(np.array(X).tolist())
    return jsonify({'prediction': list(prediction)})

But it is throwing the following exception

Object of type 'ndarray' is not JSON serializable

I tried NumPy array is not JSON serializable

but still the same error. How can i solve this issue

like image 824
user1188867 Avatar asked Aug 04 '18 11:08

user1188867


People also ask

How do I serialize a NumPy array to JSON?

Use the cls kwarg of the json. dump() and json. dumps() method to call our custom JSON Encoder, which will convert NumPy array into JSON formatted data. To serialize Numpy array into JSON we need to convert it into a list structure using a tolist() function.

How do I make an object JSON serializable?

Use toJSON() Method to make class JSON serializable So we don't need to write custom JSONEncoder. This new toJSON() serializer method will return the JSON representation of the Object. i.e., It will convert custom Python Object to JSON string.

Is NumPy array serializable?

Python's NumPy array can be used to serialize and deserialize data to and from byte representation.

How do I change Ndarray to list?

To convert a NumPy array (ndarray) to a Python list use ndarray. tolist() function, this doesn't take any parameters and returns a python list for an array. While converting to a list, it converts the items to the nearest compatible built-in Python type.


1 Answers

Try to convert your ndarray with tolist() method:

prediction = model.predict(np.array(X).tolist()).tolist()
return jsonify({'prediction': prediction})

Example with json package:

a = np.array([1,2,3,4,5]).tolist()
json.dumps({"prediction": a})

That should output:

'{"prediction": [1, 2, 3, 4, 5]}'
like image 123
Maksim Terpilowski Avatar answered Oct 26 '22 03:10

Maksim Terpilowski