Jaffermirza17's picture
Update app.py
45807b4
raw
history blame
4.08 kB
import pickle
import pandas as pd
import shap
from shap.plots._force_matplotlib import draw_additive_plot
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
# load the model from disk
loaded_model = pickle.load(open("heart_xgb.pkl", 'rb'))
# Setup SHAP
explainer = shap.Explainer(loaded_model) # PLEASE DO NOT CHANGE THIS.
# Create the main function for server
def main_func(age, sex, cp, trtbps, chol, fbs, restecg, thalachh,exng,oldpeak,slp,caa,thall):
new_row = pd.DataFrame.from_dict({'age':age,'sex':sex,
'cp':cp,'trtbps':trtbps,'chol':chol,
'fbs':fbs, 'restecg':restecg,'thalachh':thalachh,'exng':exng,
'oldpeak':oldpeak,'slp':slp,'caa':caa,'thall':thall},
orient = 'index').transpose()
prob = loaded_model.predict_proba(new_row)
shap_values = explainer(new_row)
# plot = shap.force_plot(shap_values[0], matplotlib=True, figsize=(30,30), show=False)
# plot = shap.plots.waterfall(shap_values[0], max_display=6, show=False)
plot = shap.plots.bar(shap_values[0], max_display=6, order=shap.Explanation.abs, show_data='auto', show=False)
plt.tight_layout()
local_plot = plt.gcf()
plt.close()
return {"Low Chance": float(prob[0][0]), "High Chance": 1-float(prob[0][0])}, local_plot
# Create the UI
title = "**Heart Attack Predictor & Interpreter** πŸͺ"
description1 = """This app takes info from subjects and predicts their heart attack likelihood. Do not use for medical diagnosis."""
description2 = """
To use the app, click on one of the examples, or adjust the values of the factors, and click on Analyze. 🀞
"""
with gr.Blocks(title=title) as demo:
gr.Markdown(f"## {title}")
gr.Markdown(description1)
gr.Markdown("""---""")
gr.Markdown(description2)
gr.Markdown("""---""")
age = gr.Number(label="age Score", value=80)
sex = gr.Radio(["Male", "Female"], label="Gender", type = "index", info = "What is your gender?")
cp = gr.Radio([0,1,2,3], label="Chest Pain", info="Rate the severity of your chest pain [0: none, 5: ER RIGHT NOW]:")
trtbps = gr.Number(label="Resting Blood Pressure", info = "What is your resting blood pressure?", minimum=1, maximum=200, value=4)
chol = gr.Slider(label="Cholesterol", info="What is your Cholesterol level?", minimum=1, maximum=570, value=4, step=1)
fbs = gr.Radio([1, 2, 3, 4, 5], label="Blood Sugar", info="Do you have high blood sugar? [1: Low, 5: Very High]")
restecg = gr.Slider(label="EKG Score", info="Rate your EKG score, 1 being low, 5 being high", minimum=1, maximum=5, value=4, step=1)
thalachh = gr.Number(label="Maximum Heart rate", value=4)
exng = gr.Radio(["No", "Yes"], label="Exercise Risk", info="Do you have heart risk during exercise?", type="index")
oldpeak = gr.Slider(label="Rate your ST depression during exercise:", minimum=1, maximum=10, value=5, step=0.1)
slp = gr.Radio(["unslopping", "flat", "downsloping"], label="Slope" ,info="What is the slope of your peak ST segment", type="index")
caa = gr.Slider(label="Major Blood Vessels", info="How many major blood vessels do you have?", minimum=0, maximum=4, value=2, step=1)
thall = gr.Slider(label="thall Score", info="What is your thall score?", minimum=0, maximum=3, value=2, step=1)
submit_btn = gr.Button("Analyze")
with gr.Column(visible=True) as output_col:
label = gr.Label(label = "Predicted Label")
local_plot = gr.Plot(label = 'Shap:')
submit_btn.click(
main_func,
[age, sex, cp, trtbps, chol, fbs, restecg, thalachh,exng,oldpeak,slp,caa,thall],
[label,local_plot], api_name="Heart_Predictor"
)
gr.Markdown("### Click on any of the examples below to see how it works:")
gr.Examples([[77,"Male",3,200,564, 1,2,202,1,6.2,2,4,1], [24,"Male",4,4,5,3,3,2,1,1,1,2,3]], [age, sex, cp, trtbps, chol, fbs, restecg, thalachh,exng,oldpeak,slp,caa,thall], [label,local_plot], main_func, cache_examples=True)
demo.launch()