mdurst12's picture
Update app.py
9c5187e
raw
history blame
5.49 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("XGB_softprob (1).pkl", 'rb'))
# Setup SHAP
explainer = shap.Explainer(loaded_model) # PLEASE DO NOT CHANGE THIS.
# Create the main function for server
# Create the main function for server
def main_func(CLIMATE_SCENARIO, EAL_SCORE,SOVI_SCORE,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT):
new_row = pd.DataFrame.from_dict({'CLIMATE_SCENARIO': CLIMATE_SCENARIO, 'EAL_SCORE':EAL_SCORE,'SOVI_SCORE':SOVI_SCORE,
'SOCIAL':SOCIAL,'ECONOMY':ECONOMY,'HOUSING_INFRASTRUCTURE':HOUSING_INFRASTRUCTURE,
'COMMUNITY_CAPITAL':COMMUNITY_CAPITAL,'INSTITUTIONAL':INSTITUTIONAL,'ENVIRONMENT':ENVIRONMENT}, orient = 'index').transpose()
prob = loaded_model.predict_proba(new_row)
# compute SHAP values
explainer = shap.TreeExplainer(loaded_model)
shap_values = explainer.shap_values(new_row,check_additivity=False)
plot = shap.summary_plot(shap_values[0], new_row.values, feature_names = new_row.columns)
plt.tight_layout()
local_plot = plt.gcf()
plt.close()
return {"Very Low Risk": float(prob[0][0]), "Moderately Low Risk": float(prob[0][1]), "Moderate Risk": float(prob[0][2]), "Moderately High Risk": float(prob[0][3]), "Very High Risk": float(prob[0][4])}, local_plot
# Create the UI
title = "**Climate Risk Model** 🌍"
description1 = """
This interface allows a user to populate data from three pre-selected counties or a county of their choosing. The pre-selected counties are Miami-Dade County in Florida, Washington County in Minnesota, or Falls Church County in Virginia. In order to acquire the data for a county of their choosing, a user can navigate to a team-built tableau dashboard. Either select one of three counties at bottom of page or enter custom data in the fields.
"""
description2 ="""
(https://public.tableau.com/app/profile/michael.durst/viz/ClimateChangeHackathon/ExpectedRiskbyCounty?publish=yes)
"""
description3 = """
Once the interface is pre-populated with data or a user enters data from their county, a user can experiment with the following data elements by clicking analyze and adjusting the variables available on the sliding scale.
"""
description4 = """
As an output, the user can then see the effects this variables have on the risk score and risk rating as well as see a high to low ranked order of community resilience categories.
"""
with gr.Blocks(title=title) as demo:
gr.Markdown(f"## {title}")
# gr.Markdown("""![marketing](types-of-employee-turnover.jpg)""")
gr.Markdown(description1)
# gr.Markdown("""---""")
gr.Markdown(description2)
gr.Markdown(description3)
gr.Markdown(description4)
# gr.Markdown("""---""")
with gr.Row():
with gr.Column():
CLIMATE_SCENARIO = gr.Slider(label="Climate Scenario", minimum=0, maximum=2, value=0, step=1)
EAL_SCORE = gr.Slider(label="EAL Score", minimum=0, maximum=100, value=20, step=5)
SOVI_SCORE = gr.Slider(label="SOVI Score", minimum=0, maximum=100, value=20, step=5)
SOCIAL = gr.Slider(label="Social", minimum=0, maximum=1, value=.5, step=.1)
ECONOMY = gr.Slider(label="Economy", minimum=0, maximum=1, value=.5, step=.1)
HOUSING_INFRASTRUCTURE = gr.Slider(label="Housing Infrastructure", minimum=0, maximum=1, value=.5, step=.1)
COMMUNITY_CAPITAL = gr.Slider(label="Community Capital", minimum=0, maximum=1, value=.5, step=.1)
INSTITUTIONAL = gr.Slider(label="Institutional", minimum=0, maximum=1, value=.5, step=.1)
ENVIRONMENT = gr.Slider(label="Environment", minimum=0, maximum=1, value=.5, step=.1)
submit_btn = gr.Button("Analyze")
with gr.Column(visible=True) as output_col:
label = gr.Label(label = "RISK RATING")
local_plot = gr.Plot(label = 'Shap:')
submit_btn.click(
main_func,
[CLIMATE_SCENARIO,EAL_SCORE,SOVI_SCORE,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT],
[label,local_plot], api_name="Climate Risk Model"
)
gr.Markdown("### Click on any of the examples below to see how it works:")
gr.Examples([[0, 46.23, 63.85, .564, .4703, .3068, .2161, .3623, .6264]],
[CLIMATE_SCENARIO,EAL_SCORE,SOVI_SCORE,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT],
[label,local_plot], main_func, cache_examples=True, label="Miami-Dade County, Florida")
gr.Examples([[0, 21.05, 15.37, .7231, .5359, .2884, .3828, .4070, .5015]],
[CLIMATE_SCENARIO,EAL_SCORE,SOVI_SCORE,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT],
[label,local_plot], main_func, cache_examples=True, label="Washington County, Minnesota")
gr.Examples([[0, 6.929, 4.178, .8181, .5221, .3878, .2463, .389,.3921]],
[CLIMATE_SCENARIO,EAL_SCORE,SOVI_SCORE,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT],
[label,local_plot], main_func, cache_examples=True, label="Falls Church, Virginia")
demo.launch()