nicojara commited on
Commit
4b6046e
·
verified ·
1 Parent(s): bcb086a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -60
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
@@ -7,18 +7,17 @@ import numpy as np
7
  import matplotlib.pyplot as plt
8
 
9
  # load the model from disk
10
- loaded_model = pickle.load(open("glioma_xgb.pkl", 'rb'))
11
 
12
  # Setup SHAP
13
  explainer = shap.Explainer(loaded_model) # PLEASE DO NOT CHANGE THIS.
14
 
15
  # Create the main function for server
16
- def main_func(Gender, Age_at_diagnosis, IDH1, TP53, ATRX, PTEN, EGFR, CIC, MUC16, PIK3CA, NF1, PIK3R1, FUBP1, RB1, NOTCH1, BCOR, CSMD3, SMARCA4, GRIN2A, IDH2, FAT4, PDGFRA):
17
- new_row = pd.DataFrame.from_dict({'Gender':Gender,
18
- 'Age_at_diagnosis':Age_at_diagnosis,'IDH1':IDH1,'TP53':TP53,
19
- 'ATRX':ATRX, 'PTEN':PTEN,'EGFR':EGFR,'CIC':CIC,
20
- 'MUC16':MUC16,'PIK3CA':PIK3CA,'NF1':NF1,'PIK3R1':PIK3R1, 'FUBP1': FUBP1, 'RB1': RB1, 'NOTCH1': NOTCH1,
21
- 'BCOR': BCOR, 'CSMD3': CSMD3, 'SMARCA4': SMARCA4, 'GRIN2A': GRIN2A, 'IDH2': IDH2, 'FAT4': FAT4, 'PDGFRA': PDGFRA},
22
  orient = 'index').transpose()
23
 
24
  prob = loaded_model.predict_proba(new_row)
@@ -32,72 +31,95 @@ def main_func(Gender, Age_at_diagnosis, IDH1, TP53, ATRX, PTEN, EGFR, CIC, MUC16
32
  local_plot = plt.gcf()
33
  plt.close()
34
 
35
- return {"Chance of Having GBM Tumor": 1-float(prob[0][0]), "Chance of Having LGG Tumor": float(prob[0][0])}, local_plot
 
 
 
36
 
37
  # Create the UI
38
- title = "**Glioma Predictor & Interpreter** 🪐"
39
- description1 = """This app takes info from subjects and predicts the severity of their brain tumor (LGG or GBM). Do not use for medical diagnosis."""
40
 
41
- description2 = """
42
- To use the app, click on one of the examples, or adjust the values of the factors, and click on Analyze. 🤞
43
- """
44
 
45
  with gr.Blocks(title=title) as demo:
46
  gr.Markdown(f"## {title}")
47
  gr.Markdown(description1)
48
- gr.Markdown("""---""")
49
  gr.Markdown(description2)
50
- gr.Markdown("""---""")
 
 
 
 
 
 
 
 
 
 
51
 
 
52
  with gr.Row():
53
- Gender = gr.Radio(["Female", "Male"], label="Gender", type = "index")
54
- Age_at_diagnosis = gr.Number(label="Age at Diagnosis")
55
- with gr.Row():
56
- IDH1 = gr.Radio(["No", "Yes"], label="IDH1 Mutation", type="index")
57
- TP53 = gr.Radio(["No", "Yes"], label="TP53 Mutation", type="index")
58
- ATRX = gr.Radio(["No", "Yes"], label="ATRX Mutation", type="index")
59
- with gr.Row():
60
- PTEN = gr.Radio(["No", "Yes"], label="PTEN Mutation", type="index")
61
- EGFR = gr.Radio(["No", "Yes"], label="EGFR Mutation", type="index")
62
- CIC = gr.Radio(["No", "Yes"], label="CIC Mutation", type="index")
63
- with gr.Row():
64
- MUC16 = gr.Radio(["No", "Yes"], label="MUC16 Mutation", type="index")
65
- PIK3CA = gr.Radio(["No", "Yes"], label="PIK3CA Mutation", type="index")
66
- NF1 = gr.Radio(["No", "Yes"], label="NF1 Mutation", type="index")
67
- with gr.Row():
68
- PIK3R1 = gr.Radio(["No", "Yes"], label="PIK3R1 Mutation", type="index")
69
- FUBP1 = gr.Radio(["No", "Yes"], label="FUBP1 Mutation", type="index")
70
- RB1 = gr.Radio(["No", "Yes"], label="RB1 Mutation", type="index")
71
  with gr.Row():
72
- NOTCH1 = gr.Radio(["No", "Yes"], label="NOTCH1 Mutation", type="index")
73
- BCOR = gr.Radio(["No", "Yes"], label="BCOR Mutation", type="index")
74
- CSMD3 = gr.Radio(["No", "Yes"], label="CSMD3 Mutation", type="index")
75
- with gr.Row():
76
- SMARCA4 = gr.Radio(["No", "Yes"], label="SMAECA4 Mutation", type="index")
77
- GRIN2A = gr.Radio(["No", "Yes"], label="GRIN2A Mutation", type="index")
78
- IDH2 = gr.Radio(["No", "Yes"], label="IDH2 Mutation", type="index")
79
- FAT4 = gr.Radio(["No", "Yes"], label="FAT4 Mutation", type="index")
80
- PDGFRA = gr.Radio(["No", "Yes"], label="PDGFRA Mutation", type="index")
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
- submit_btn = gr.Button("Analyze")
 
 
 
 
 
 
 
 
89
 
 
90
  with gr.Column(visible=True) as output_col:
91
- label = gr.Label(label = "Predicted Label")
92
- local_plot = gr.Plot(label = 'Grade:')
 
 
 
 
 
 
93
 
94
  submit_btn.click(
95
- main_func,
96
- [Gender, Age_at_diagnosis, IDH1, TP53, ATRX, PTEN, EGFR, CIC, MUC16, PIK3CA, NF1, PIK3R1, FUBP1, RB1, NOTCH1, BCOR, CSMD3, SMARCA4, GRIN2A, IDH2, FAT4, PDGFRA],
97
- [label,local_plot], api_name="Glioma_Predictor"
 
98
  )
99
-
100
- gr.Markdown("### Click on any of the examples below to see how it works:")
101
- gr.Examples([["Male",24,"Yes","No","Yes","Yes","Yes","No","Yes","Yes","Yes","Yes","Yes","No","No","No","No","Yes","No","Yes","No","Yes"], ["Male",70,"No","No","No","No","No","No","No","No","No","Yes","No","Yes","No","No","No","No","No","No","No", "No"]], [Gender, Age_at_diagnosis, IDH1, TP53, ATRX, PTEN, EGFR, CIC, MUC16, PIK3CA, NF1, PIK3R1, FUBP1, RB1, NOTCH1, BCOR, CSMD3, SMARCA4, GRIN2A, IDH2, FAT4, PDGFRA], [label,local_plot], main_func, cache_examples=True)
102
 
103
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
  import pandas as pd
3
  import shap
4
  from shap.plots._force_matplotlib import draw_additive_plot
 
7
  import matplotlib.pyplot as plt
8
 
9
  # load the model from disk
10
+ loaded_model = pickle.load(open("salar_xgb_team.pkl", 'rb'))
11
 
12
  # Setup SHAP
13
  explainer = shap.Explainer(loaded_model) # PLEASE DO NOT CHANGE THIS.
14
 
15
  # Create the main function for server
16
+ def main_func(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({'age':age,
19
+ 'education-num':education_num,'sex':sex,'capital-gain':capital_gain,
20
+ 'capital-loss':capital_loss, 'hours-per-week':hours_per_week},
 
21
  orient = 'index').transpose()
22
 
23
  prob = loaded_model.predict_proba(new_row)
 
31
  local_plot = plt.gcf()
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
  # Create the UI
40
+ title = "**Household Income Predictor** 💰"
41
+ description1 = """This app uses your input to predict whether a household earns more or less than $50K per year"""
42
 
43
+ description2 = """Adjust the values below and click 'Analyze' to see the prediction and explanation."""
 
 
44
 
45
  with gr.Blocks(title=title) as demo:
46
  gr.Markdown(f"## {title}")
47
  gr.Markdown(description1)
48
+ gr.Markdown("---")
49
  gr.Markdown(description2)
50
+ gr.Markdown("---")
51
+
52
+ # 🎛 Preset scenario dropdown
53
+ scenario = gr.Dropdown(
54
+ ["Select a Sample",
55
+ "👨‍💻 Young Tech Worker: 28 yrs, college degree, 45 hrs/week",
56
+ "👵 Retired Part-Timer: 65 yrs, no college, 20 hrs/week",
57
+ "👩‍🏫 Mid-Career Teacher: 42 yrs, 14 education years, 38 hrs/week",
58
+ "👨‍🔧 Manual Laborer: 50 yrs, 9 education years, 60 hrs/week"],
59
+ label="📋 Choose a Sample Profile (optional — autofills values to explore common cases)"
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  with gr.Row():
67
+ sex = gr.Radio(["Male", "Female"], label="🧍 Sex")
68
+ capital_gain = gr.Number(label="📈 Capital Gain", value=0)
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]
78
+ elif scenario_choice == "👵 Retired Part-Timer: 65 yrs, no college, 20 hrs/week":
79
+ return [65, 8, "Female", 0, 0, 20]
80
+ elif scenario_choice == "👩‍🏫 Mid-Career Teacher: 42 yrs, 14 education years, 38 hrs/week":
81
+ return [42, 14, "Female", 0, 0, 38]
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] # Default values
86
+
87
+ scenario.change(
88
+ fn=fill_scenario,
89
+ inputs=[scenario],
90
+ outputs=[age, education_num, sex, capital_gain, capital_loss, hours_per_week]
91
+ )
92
 
93
+ # 🧠 Prediction output
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
+ # 🧠 Wrap predict + confidence slider logic
100
+ def wrapped_main(age, education_num, sex, capital_gain, capital_loss, hours_per_week):
101
+ result, shap_plot = main_func(age, education_num, sex, capital_gain, capital_loss, hours_per_week)
102
+ return result, float(result["Chance of Earning > $50K"]) * 100, shap_plot
103
 
104
  submit_btn.click(
105
+ wrapped_main,
106
+ [age, education_num, sex, capital_gain, capital_loss, hours_per_week],
107
+ [label, confidence, local_plot],
108
+ api_name="Salary_Predictor"
109
  )
 
 
 
110
 
111
+ gr.Markdown("### 🧪 Try Some Examples:")
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
+ [label, confidence, local_plot],
119
+ wrapped_main,
120
+ cache_examples=True
121
+ )
122
+
123
+ demo.launch()
124
+
125
+