File size: 7,783 Bytes
7fbeebd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bdedaf
7fbeebd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5504b9a
7fbeebd
 
 
 
 
 
 
5504b9a
7fbeebd
 
 
b2b4c9a
7fbeebd
 
 
 
e110036
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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.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(EAL_SCORE,SOVI_SCORE,RESL_SCORE,DROUGHT_RISKS,EARTHQUAKE_RISKS,HURICANE_RISKS,TORNADO_RISKS,WILDFIRE_RISKS,WINTERWEATHER_RISKS,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT):
    
    new_row = pd.DataFrame.from_dict({'EAL_SCORE':EAL_SCORE,'SOVI_SCORE':SOVI_SCORE, 'RESL_SCORE':RESL_SCORE,
              'DROUGHT_RISKS':DROUGHT_RISKS,'EARTHQUAKE_RISKS':EARTHQUAKE_RISKS,'HURICANE_RISKS':HURICANE_RISKS,
              'TORNADO_RISKS':TORNADO_RISKS,'WILDFIRE_RISKS':WILDFIRE_RISKS,'WINTERWEATHER_RISKS':WINTERWEATHER_RISKS,
              'SOCIAL':SOCIAL,'ECONOMY':ECONOMY,'HOUSING_INFRASTRUCTURE':HOUSING_INFRASTRUCTURE,
              'COMMUNNITY_CAPITAL':COMMUNNITY_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, new_row.values, plot_type="bar", class_names= class_names, feature_names = new_row.columns)
    plot = shap.summary_plot(shap_values[1], new_row.values, feature_names = new_row.columns)
    
    

    # plot = shap.waterfall_plot(shap.Explanation(values=shap_values[0][0], 
    #                                           base_values=explainer.expected_value[0], data=X_test.iloc[0],  
    #                                      feature_names=X_test.columns.tolist()))
    
    # shap_values = explainer(new_row, check_additivity=False)
    # 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.waterfall_plot(explainer.base_values[0], shap_values[0][0], X[0])
    # 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 {"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 = """
The BRIC index considers six broad categories of community disaster resilience: social, economic, community capital, institutional, infrastructural, and environmental at the county level. Used as an initial baseline for monitoring existing attributes of resilience to natural hazards, BRIC can be used to compare places to one another, to determine the specific drivers of resilience for counties, and to monitor improvements in resilience over time. 
"""

description2 = """
To use the app, click on one of the examples, or adjust the values of the six factors, and click on Analyze. ✨ 
""" 

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("""---""")
    with gr.Row():        
        with gr.Column():                 
            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)
            RESL_SCORE = gr.Slider(label="RESILIENCE Score", minimum=0, maximum=100, value=20, step=5)
            DROUGHT_RISKS = gr.Slider(label="DROUGHT Score", minimum=0, maximum=100, value=20, step=5)
            EARTHQUAKE_RISKS = gr.Slider(label="EARTHQUAKE Score", minimum=0, maximum=100, value=20, step=5)
            HURICANE_RISKS = gr.Slider(label="HURICANE Score", minimum=0, maximum=100, value=20, step=5)
            TORNADO_RISKS = gr.Slider(label="TORNADO Score", minimum=0, maximum=100, value=20, step=5)
            WILDFIRE_RISKS = gr.Slider(label="WILDFIRE Score", minimum=0, maximum=100, value=20, step=5)
            WINTERWEATHER_RISKS = gr.Slider(label="WINTER WEATHER Score", minimum=0, maximum=100, value=20, step=5)            
            SOCIAL = gr.Slider(label="Social Score", minimum=0, maximum=1, value=.5, step=.1)
            ECONOMY = gr.Slider(label="Economic Score", minimum=0, maximum=1, value=.5, step=.1)
            HOUSING_INFRASTRUCTURE = gr.Slider(label="Housing Score", minimum=0, maximum=1, value=.5, step=.1)
            COMMUNNITY_CAPITAL = gr.Slider(label="Community Capital Score", minimum=0, maximum=1, value=.5, step=.1)
            INSTITUTIONAL = gr.Slider(label="Institutional Score", minimum=0, maximum=1, value=.5, step=.1)
            ENVIRONMENT = gr.Slider(label="Environment Score", 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,
                [EAL_SCORE,SOVI_SCORE,RESL_SCORE,DROUGHT_RISKS,EARTHQUAKE_RISKS,HURICANE_RISKS,TORNADO_RISKS,WILDFIRE_RISKS,WINTERWEATHER_RISKS,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNNITY_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.Markdown("Miami-Dade County, Florida")
    gr.Examples([[32.03, 68.86, 50.5, 50.5, .1, 30, 19.41, 57.47, 1.024, 45.16, .5441, .4393, .4095, .2630, .3799, .3773]], 
                [EAL_SCORE,SOVI_SCORE,RESL_SCORE,DROUGHT_RISKS,EARTHQUAKE_RISKS,HURICANE_RISKS,TORNADO_RISKS,WILDFIRE_RISKS,WINTERWEATHER_RISKS,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT], 
                [label,local_plot], main_func, cache_examples=True)
    gr.Textbox(label="Miami-Dade County, Florida")
    gr.Examples([[46.24, 63.85, 53.39, 31.27, 6.771, 58.93, 76.76, 54.54, 0, .564, .4703, .3068, .2161, .3623, .6264]], 
                [EAL_SCORE,SOVI_SCORE,RESL_SCORE,DROUGHT_RISKS,EARTHQUAKE_RISKS,HURICANE_RISKS,TORNADO_RISKS,WILDFIRE_RISKS,WINTERWEATHER_RISKS,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT], 
                [label,local_plot], main_func, cache_examples=True)
    gr.Markdown("Washington County, Minnesota")
    gr.Examples([[21.06, 15.37, 58.77, 2.32, .5035, 0, 11.98, 4.957, 6.808, .7231, .5359, .2884, .328, .407, .5015]], 
                [EAL_SCORE,SOVI_SCORE,RESL_SCORE,DROUGHT_RISKS,EARTHQUAKE_RISKS,HURICANE_RISKS,TORNADO_RISKS,WILDFIRE_RISKS,WINTERWEATHER_RISKS,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT], 
                [label,local_plot], main_func, cache_examples=True)
    gr.Markdown("Falls Church, Virginia")
    gr.Examples([[6.947, 4.178, 56.86, 0, .1587, .5027, 1.071, 0, 0, .8181, .5221, .3878, .2463, .389, .3921]], 
                [EAL_SCORE,SOVI_SCORE,RESL_SCORE,DROUGHT_RISKS,EARTHQUAKE_RISKS,HURICANE_RISKS,TORNADO_RISKS,WILDFIRE_RISKS,WINTERWEATHER_RISKS,SOCIAL,ECONOMY,HOUSING_INFRASTRUCTURE,COMMUNNITY_CAPITAL,INSTITUTIONAL,ENVIRONMENT], 
                [label,local_plot], main_func, cache_examples=True)

demo.launch()