Object of type 'ndarray' is not JSON serializable

不羁岁月 提交于 2021-02-16 15:50:28

问题


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


回答1:


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]}'


来源:https://stackoverflow.com/questions/51685322/object-of-type-ndarray-is-not-json-serializable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!