Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import pickle
|
| 2 |
import pandas as pd
|
| 3 |
import shap
|
| 4 |
from shap.plots._force_matplotlib import draw_additive_plot
|
|
@@ -6,60 +6,62 @@ import gradio as gr
|
|
| 6 |
import numpy as np
|
| 7 |
import matplotlib.pyplot as plt
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
loaded_model = pickle.load(open("
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
explainer = shap.Explainer(loaded_model)
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
def
|
| 17 |
sex = 1 if sex == "Female" else 0
|
| 18 |
-
new_row = pd.DataFrame.from_dict({
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
| 24 |
|
|
|
|
|
|
|
|
|
|
| 25 |
shap_values = explainer(new_row)
|
| 26 |
-
# plot = shap.force_plot(shap_values[0], matplotlib=True, figsize=(30,30), show=False)
|
| 27 |
-
# plot = shap.plots.waterfall(shap_values[0], max_display=6, show=False)
|
| 28 |
plot = shap.plots.bar(shap_values[0], max_display=6, order=shap.Explanation.abs, show_data='auto', show=False)
|
| 29 |
-
|
| 30 |
plt.tight_layout()
|
| 31 |
-
|
| 32 |
plt.close()
|
| 33 |
-
|
| 34 |
-
return {
|
| 35 |
-
"Chance of Earning > $50K": float(prob[0][1]),
|
| 36 |
-
"Chance of Earning ≤ $50K": float(prob[0][0])
|
| 37 |
-
}, local_plot
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
with gr.Blocks(title=title) as demo:
|
| 46 |
gr.Markdown(f"## {title}")
|
| 47 |
-
gr.Markdown(
|
| 48 |
gr.Markdown("---")
|
| 49 |
-
gr.Markdown(
|
| 50 |
gr.Markdown("---")
|
| 51 |
|
| 52 |
-
# 🎛 Preset scenario dropdown
|
| 53 |
scenario = gr.Dropdown(
|
| 54 |
-
["Select a Sample",
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
)
|
| 61 |
|
| 62 |
-
# 🎯 Inputs
|
| 63 |
with gr.Row():
|
| 64 |
age = gr.Number(label="🧓 Age", value=35)
|
| 65 |
education_num = gr.Number(label="🎓 Education Level (numeric)", value=10)
|
|
@@ -69,9 +71,6 @@ with gr.Blocks(title=title) as demo:
|
|
| 69 |
capital_loss = gr.Number(label="📉 Capital Loss", value=0)
|
| 70 |
hours_per_week = gr.Number(label="⏱ Hours per Week", value=40)
|
| 71 |
|
| 72 |
-
submit_btn = gr.Button("🔎 Analyze")
|
| 73 |
-
|
| 74 |
-
# 🔁 Handle preset scenario changes
|
| 75 |
def fill_scenario(scenario_choice):
|
| 76 |
if scenario_choice == "👨💻 Young Tech Worker: 28 yrs, college degree, 45 hrs/week":
|
| 77 |
return [28, 16, "Male", 0, 0, 45]
|
|
@@ -82,7 +81,7 @@ with gr.Blocks(title=title) as demo:
|
|
| 82 |
elif scenario_choice == "👨🔧 Manual Laborer: 50 yrs, 9 education years, 60 hrs/week":
|
| 83 |
return [50, 9, "Male", 0, 0, 60]
|
| 84 |
else:
|
| 85 |
-
return [35, 10, "Male", 0, 0, 40]
|
| 86 |
|
| 87 |
scenario.change(
|
| 88 |
fn=fill_scenario,
|
|
@@ -90,34 +89,27 @@ with gr.Blocks(title=title) as demo:
|
|
| 90 |
outputs=[age, education_num, sex, capital_gain, capital_loss, hours_per_week]
|
| 91 |
)
|
| 92 |
|
| 93 |
-
|
| 94 |
-
with gr.Column(visible=True) as output_col:
|
| 95 |
-
label = gr.Label(label="🧠 Predicted Income")
|
| 96 |
-
confidence = gr.Slider(0, 100, value=50, label="📊 Confidence in > $50K", interactive=False)
|
| 97 |
-
local_plot = gr.Plot(label="🔍 Top SHAP Features")
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
|
| 104 |
submit_btn.click(
|
| 105 |
-
|
| 106 |
[age, education_num, sex, capital_gain, capital_loss, hours_per_week],
|
| 107 |
-
[
|
| 108 |
-
api_name="
|
| 109 |
)
|
| 110 |
|
| 111 |
-
gr.Markdown("### 🧪 Try
|
| 112 |
gr.Examples(
|
| 113 |
-
[
|
| 114 |
-
[28, 16, "Male", 0, 0, 45],
|
| 115 |
-
[60, 8, "Female", 0, 0, 25]
|
| 116 |
-
],
|
| 117 |
[age, education_num, sex, capital_gain, capital_loss, hours_per_week],
|
| 118 |
-
[
|
| 119 |
-
|
| 120 |
cache_examples=True
|
| 121 |
)
|
| 122 |
|
| 123 |
-
demo.launch()
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
import pandas as pd
|
| 3 |
import shap
|
| 4 |
from shap.plots._force_matplotlib import draw_additive_plot
|
|
|
|
| 6 |
import numpy as np
|
| 7 |
import matplotlib.pyplot as plt
|
| 8 |
|
| 9 |
+
# Load your regression model (e.g., XGBoost Regressor)
|
| 10 |
+
loaded_model = pickle.load(open("income_regressor_model.pkl", 'rb'))
|
| 11 |
|
| 12 |
+
# SHAP setup (do not change)
|
| 13 |
+
explainer = shap.Explainer(loaded_model)
|
| 14 |
|
| 15 |
+
# Define the main prediction function
|
| 16 |
+
def predict_affordability(age, education_num, sex, capital_gain, capital_loss, hours_per_week):
|
| 17 |
sex = 1 if sex == "Female" else 0
|
| 18 |
+
new_row = pd.DataFrame.from_dict({
|
| 19 |
+
'age': age,
|
| 20 |
+
'education-num': education_num,
|
| 21 |
+
'sex': sex,
|
| 22 |
+
'capital-gain': capital_gain,
|
| 23 |
+
'capital-loss': capital_loss,
|
| 24 |
+
'hours-per-week': hours_per_week
|
| 25 |
+
}, orient='index').transpose()
|
| 26 |
|
| 27 |
+
predicted_income = loaded_model.predict(new_row)[0]
|
| 28 |
+
affordable = predicted_income >= 80000 # Car price threshold
|
| 29 |
+
|
| 30 |
shap_values = explainer(new_row)
|
|
|
|
|
|
|
| 31 |
plot = shap.plots.bar(shap_values[0], max_display=6, order=shap.Explanation.abs, show_data='auto', show=False)
|
|
|
|
| 32 |
plt.tight_layout()
|
| 33 |
+
plot_fig = plt.gcf()
|
| 34 |
plt.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
affordability_msg = (
|
| 37 |
+
f"✅ You can likely afford a $40K car! (Predicted Income: ${predicted_income:,.2f})"
|
| 38 |
+
if affordable else
|
| 39 |
+
f"❌ A $40K car may be unaffordable. (Predicted Income: ${predicted_income:,.2f})"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
return affordability_msg, predicted_income, plot_fig
|
| 43 |
|
| 44 |
+
# Gradio UI
|
| 45 |
+
title = "**Car Affordability Predictor 🚗**"
|
| 46 |
+
desc1 = "This app uses your input to estimates annual houshold income and tells you if you can afford a $40,000 car."
|
| 47 |
+
desc2 = "Fill in the values below to get a prediction and explanation."
|
| 48 |
|
| 49 |
with gr.Blocks(title=title) as demo:
|
| 50 |
gr.Markdown(f"## {title}")
|
| 51 |
+
gr.Markdown(desc1)
|
| 52 |
gr.Markdown("---")
|
| 53 |
+
gr.Markdown(desc2)
|
| 54 |
gr.Markdown("---")
|
| 55 |
|
|
|
|
| 56 |
scenario = gr.Dropdown(
|
| 57 |
+
["Select a Sample",
|
| 58 |
+
"👨💻 Young Tech Worker: 28 yrs, college degree, 45 hrs/week",
|
| 59 |
+
"👵 Retired Part-Timer: 65 yrs, no college, 20 hrs/week",
|
| 60 |
+
"👩🏫 Mid-Career Teacher: 42 yrs, 14 education years, 38 hrs/week",
|
| 61 |
+
"👨🔧 Manual Laborer: 50 yrs, 9 education years, 60 hrs/week"],
|
| 62 |
+
label="📋 Choose a Sample Profile (optional)"
|
| 63 |
)
|
| 64 |
|
|
|
|
| 65 |
with gr.Row():
|
| 66 |
age = gr.Number(label="🧓 Age", value=35)
|
| 67 |
education_num = gr.Number(label="🎓 Education Level (numeric)", value=10)
|
|
|
|
| 71 |
capital_loss = gr.Number(label="📉 Capital Loss", value=0)
|
| 72 |
hours_per_week = gr.Number(label="⏱ Hours per Week", value=40)
|
| 73 |
|
|
|
|
|
|
|
|
|
|
| 74 |
def fill_scenario(scenario_choice):
|
| 75 |
if scenario_choice == "👨💻 Young Tech Worker: 28 yrs, college degree, 45 hrs/week":
|
| 76 |
return [28, 16, "Male", 0, 0, 45]
|
|
|
|
| 81 |
elif scenario_choice == "👨🔧 Manual Laborer: 50 yrs, 9 education years, 60 hrs/week":
|
| 82 |
return [50, 9, "Male", 0, 0, 60]
|
| 83 |
else:
|
| 84 |
+
return [35, 10, "Male", 0, 0, 40]
|
| 85 |
|
| 86 |
scenario.change(
|
| 87 |
fn=fill_scenario,
|
|
|
|
| 89 |
outputs=[age, education_num, sex, capital_gain, capital_loss, hours_per_week]
|
| 90 |
)
|
| 91 |
|
| 92 |
+
submit_btn = gr.Button("🔍 Predict Affordability")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
+
with gr.Column(visible=True):
|
| 95 |
+
output_label = gr.Textbox(label="💬 Result")
|
| 96 |
+
predicted_income = gr.Number(label="📈 Predicted Annual Income ($)", interactive=False)
|
| 97 |
+
shap_plot = gr.Plot(label="🔍 Top SHAP Features")
|
| 98 |
|
| 99 |
submit_btn.click(
|
| 100 |
+
predict_affordability,
|
| 101 |
[age, education_num, sex, capital_gain, capital_loss, hours_per_week],
|
| 102 |
+
[output_label, predicted_income, shap_plot],
|
| 103 |
+
api_name="Car_Affordability"
|
| 104 |
)
|
| 105 |
|
| 106 |
+
gr.Markdown("### 🧪 Try Examples:")
|
| 107 |
gr.Examples(
|
| 108 |
+
[[28, 16, "Male", 0, 0, 45], [60, 8, "Female", 0, 0, 25]],
|
|
|
|
|
|
|
|
|
|
| 109 |
[age, education_num, sex, capital_gain, capital_loss, hours_per_week],
|
| 110 |
+
[output_label, predicted_income, shap_plot],
|
| 111 |
+
predict_affordability,
|
| 112 |
cache_examples=True
|
| 113 |
)
|
| 114 |
|
| 115 |
+
demo.launch()
|