| 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 |
|
|
| |
| loaded_model = pickle.load(open("heart_xgb.pkl", 'rb')) |
|
|
| |
| explainer = shap.Explainer(loaded_model) |
|
|
| gender = {"Female":0,"Male":1} |
| chest = {"typical angina":1,"atypical angina":2,"non-anginal pain":3,"asymptomatic":4} |
| choice = {"True":1, "False":0} |
| rest = {"Probable or Definite Left Ventricular Hypertrophy by Estes' Criteria":2, "Having ST - T Wave Abnormality":1,"Normal Value":0} |
| ex = {"yes":1, "no":0} |
| sl = {"upsloping":2, "flat":1,"downsloping":0} |
| th = {"Reversible Defect":3, "Normal Blood Flow":2, "Fixed Defect":1} |
|
|
| |
| 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':gender[sex], |
| 'cp':chest[cp],'trtbps':trtbps,'chol':chol, 'fbs':choice[fbs], 'restecg':rest[restecg], |
| 'thalachh':thalachh, 'exng':ex[exng], 'oldpeak':oldpeak, 'slp':sl[slp], 'caa':caa, 'thall':th[thall]}, orient = 'index').transpose() |
| |
| prob = loaded_model.predict_proba(new_row) |
| |
| shap_values = explainer(new_row) |
| |
| |
| 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 Heart Attack Chance": float(prob[0][0]), "High Heart Attack Chance": 1-float(prob[0][0])}, local_plot |
|
|
| |
| 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. |
| |
| Data Dictionary: |
| |
| Age : Age of the patient |
| |
| Sex : Sex of the patient |
| |
| cp : Chest Pain type |
| |
| trtbps: Resting Blood Pressure (in mm Hg) |
| |
| chol : Cholestoral in mg/dl Fetched via BMI Sensor |
| |
| fbs : (fasting blood sugar > 120 mg/dl) |
| |
| rest_ecg : Resting Electrocardiographic Results |
| |
| thalachh : Maximum Heart Rate Achieved |
| |
| exng: Exercise Induced Angina |
| |
| oldpeak : Short-Term Depression Induced by Exercise Relative to Rest |
| |
| slp : Slope of the Peak Exercise Short-Term Segment |
| |
| caa : Number of Major Vessels (0-3) |
| |
| thall : Thalassemia |
| """ |
|
|
| with gr.Blocks(title=title) as demo: |
| gr.Markdown(f"## {title}") |
| |
| gr.Markdown(description1) |
| gr.Markdown("""---""") |
| gr.Markdown(description2) |
| gr.Markdown("""---""") |
| |
| with gr.Row(): |
| with gr.Column(): |
| age = gr.Slider(label="age score", minimum=0, maximum=90, value=40, step=1) |
| sex = gr.Dropdown(label="sex score", choices =["Female","Male"]) |
| cp = gr.Radio(label="cp score", choices = ["typical angina", "atypical angina", "non-anginal pain", "asymptomatic"]) |
| trtbps = gr.Slider(label="trtbps Score", minimum=90, maximum=200, value=90, step=1) |
| chol = gr.Slider(label="chol Score", minimum=120, maximum=570, value=120, step=1) |
| fbs = gr.Radio(label="fbs Score", choices = ["True", "False"]) |
| restecg = gr.Dropdown(label="restecg Score", choices = ["Probable or Definite Left Ventricular Hypertrophy by Estes' Criteria", "Having ST - T Wave Abnormality","Normal Value"]) |
| with gr.Column(): |
| thalachh = gr.Slider(label="thalachh Score", minimum=70, maximum=210, value=70, step=1) |
| exng = gr.Slider(label="exng Score", choices = ["yes","no"]) |
| oldpeak = gr.Slider(label="oldpeak Score", minimum=0.0, maximum=6.5, value=0, step=0.1) |
| slp = gr.Radio(label="slp Score", choices = ["upsloping", "flat", "downsloping"]) |
| caa = gr.Slider(label="caa Score", minimum=0, maximum=3, value=0, step=1) |
| thall = gr.Slider(label="thall Score", choices = ["Reversible Defect", "Normal Blood Flow", "Fixed Defect"]) |
| |
| with gr.Row(): |
| with gr.Column(): |
| 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="Employee_Turnover" |
| ) |
| |
| gr.Markdown("### Click on any of the examples below to see how it works:") |
| gr.Examples([[24,"Male","typical angina",150,300,"True","Probable or Definite Left Ventricular Hypertrophy by Estes' Criteria",90,"yes",1,"flat",3,"Reversible Defect"], [20,"Female","asymptomatic",50,400,"True","Having ST - T Wave Abnormality",150,"no",3.5,"upsloping",3,"Fixed Defect"]], [age, sex, cp, trtbps, chol, fbs, restecg, thalachh, exng, oldpeak, slp, caa, thall], [label,local_plot], main_func, cache_examples=True) |
|
|
| demo.launch() |