[ad_1]
I use the following code, saving the scaler and models from a model that predicts heart disease. I’m now trying to use the code to send a JSON via Postman, but I’m running into the following error: TypeError: Object of type ndarray is not JSON serializable. After doing some Googling, it looks like I would have to use json.dumps(cls=NumPyArrayEncoder) or pd.Series(your_array).to_json(orient=”values”). What I don’t understand is where to add this? What do I use this code on, the model before it’s saved as an h5? Do I modify the inputs for the model? Do I also use json dumps on the saved scalers?
from flask import Flask, request, jsonify
import numpy as np
from tensorflow.keras.models import load_model
import joblib
def return_prediction(model, scaler, sample_json):
age = sample_json["age"]
sex = sample_json["sex"]
cp = sample_json['cp']
trestbps = sample_json['trestbps']
chol = sample_json['chol']
fbs = sample_json['fbs']
restecg = sample_json['restecg']
thalach = sample_json['thalach']
exang = sample_json['exang']
oldpeak = sample_json['oldpeak']
slope = sample_json['slope']
ca = sample_json['ca']
thal = sample_json['thal']
heart = [[age, sex, cp, trestbps, chol, fbs, restecg,
thalach, exang, oldpeak, slope, ca, thal]]
heart = scaler.transform(heart)
classes = np.array(['0','1'])
class_ind = model.predict(heart)
return classes
app = Flask(__name__)
@app.route("/")
def index():
return '<h1>FLASK RUNNING</h1>'
heart_model = load_model("heart_disease_model_bry.h5")
heart_scaler = joblib.load("heart_scaler_bry.pkl")
@app.route('/api/heart',methods=['POST'])
def prediction():
content = request.json
results = return_prediction(heart_model, heart_scaler, content)
return jsonify(results)
if __name__=='__main__':
app.run()
JSON using as a sample to request a prediction via Postman:
{"age":53,
"sex":1,
"cp":0,
"trestbps":125,
"chol":212,
"fbs":0,
"restecg":1,
"thalach":168,
"exang":0,
"oldpeak":1.0,
"slope":2,
"ca":2,
"thal":3}
[ad_2]