Group_5 / app.py
tby4rr's picture
Update app.py
b0c6626 verified
raw
history blame
4.53 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("cdc_diabetes_health_indicators.pkl", 'rb'))
# Setup SHAP
explainer = shap.Explainer(loaded_model) # PLEASE DO NOT CHANGE THIS.
# Create the main function for server
def main_func(ID, Diabetes_binary, HighBP, HighCol, CholCheck, BMI, Smoker, Stroke, HeartDiseaseorAttack, PhysActivity, Fruits, Veggies, HvyAlcoholConsump, AnyHealthcare, NoDocbcCost, GenHlth, MentHlth, PhysHealth, DiffWalk, Sex, Age, Education, Income):
new_row = pd.DataFrame.from_dict({'ID':ID,'Diabetes_binary':Diabetes_binary,
'HighBP':HighBP,'HighCol':HighCol,'CholCheck':CholCheck,
'BMI':BMI, 'Smoker':Smoker,'Stroke':Stroke,'HeartDiseaseorAttack':HeartDiseaseorAttack,
'PhysActivity':PhysActivity,'Fruits':Fruits,'Veggies':Veggies,'HvyAlcoholConsump':HvyAlcoholConsump,
'AnyHealthcare':AnyHealthcare, 'NoDocbcCost':NoDocbcCost, 'GenHlth':GenHlth, 'MenHlth': MenHlth,
'PhysHealth':PhysHealth, 'DiffWalk':DiffWalk, 'Sex':Sex, 'Age':Age, 'Education':Education, 'Income':Income},
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=40)
sex = gr.Slider(label="sex Score", minimum=0, maximum=1, value=1, step=1)
cp = gr.Slider(label="cp Score", minimum=1, maximum=5, value=4, step=1)
trtbps = gr.Slider(label="trtbps Score", minimum=1, maximum=5, value=4, step=1)
chol = gr.Slider(label="chol Score", minimum=1, maximum=5, value=4, step=1)
fbs = gr.Slider(label="fbs Score", minimum=1, maximum=5, value=4, step=1)
restecg = gr.Slider(label="restecg Score", minimum=1, maximum=5, value=4, step=1)
thalachh = gr.Slider(label="thalachh Score", minimum=1, maximum=5, value=4, step=1)
exng = gr.Slider(label="exng Score", minimum=1, maximum=5, value=4, step=1)
oldpeak = gr.Slider(label="oldpeak Score", minimum=1, maximum=5, value=4, step=1)
slp = gr.Slider(label="slp Score", minimum=1, maximum=5, value=4, step=1)
caa = gr.Slider(label="caa Score", minimum=1, maximum=5, value=4, step=1)
thall = gr.Slider(label="thall Score", minimum=1, maximum=5, value=4, 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,
[ID, Diabetes_binary, HighBP, HighCol, CholCheck, BMI, Smoker, Stroke, HeartDiseaseorAttack, PhysActivity, Fruits, Veggies, HvyAlcoholConsump, AnyHealthcare, NoDocbcCost, GenHlth, MentHlth, PhysHealth, DiffWalk, Sex, Age, Education, Income],
[label,local_plot], api_name="Diabetes_Predictor"
)
gr.Markdown("### Click on any of the examples below to see how it works:")
gr.Examples([[24,0,4,4,5,5,4,4,5,5,1,2,3], [24,0,4,4,5,3,3,2,1,1,1,2,3]], [ID, Diabetes_binary, HighBP, HighCol, CholCheck, BMI, Smoker, Stroke, HeartDiseaseorAttack, PhysActivity, Fruits, Veggies, HvyAlcoholConsump, AnyHealthcare, NoDocbcCost, GenHlth, MentHlth, PhysHealth, DiffWalk, Sex, Age, Education, Income], [label,local_plot], main_func, cache_examples=True)
demo.launch()