Repository navigation
Expand file tree
/
Copy pathP01_shiny.qmd
More file actions
345 lines (296 loc) · 11.5 KB
/
Copy pathP01_shiny.qmd
File metadata and controls
345 lines (296 loc) · 11.5 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
---
title: "Student Academic Risk Predictor — Interactive"
format: html
server: shiny
---
### Interactive prediction
```{python}
#| context: setup
import warnings
warnings.filterwarnings("ignore", message="More column widths than children")
warnings.filterwarnings("ignore")
import io
import pickle
import numpy as np
import pandas as pd
import shap
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
model = pickle.load(open("/Users/apple/degree/BDA/model_py312.pkl", "rb"))
scaler = pickle.load(open("/Users/apple/degree/BDA/scaler_py312.pkl", "rb"))
explainer = shap.TreeExplainer(model)
THRESHOLD = 0.1546
FEATURES = [
"age", "gender", "attendance_pct", "assignment_avg", "quiz_avg", "midterm_score",
"study_hours_week", "previous_gpa", "absences", "internet_access", "extracurricular",
"prog_Computer Science", "prog_Data Science", "prog_IT", "prog_Software Engineering",
"engagement_score"
]
GENDER_MAP = {"Male": 0, "Female": 1}
PROGRAMMES = ["Computer Science", "Data Science", "IT", "Software Engineering"]
# Background sample for global SHAP beeswarm
BG = (
pd.read_csv("/Users/apple/degree/BDA/P01_data_cleaned.csv")[FEATURES]
.sample(n=200, random_state=42)
)
BG_SCALED = scaler.transform(BG)
BG_EXPLANATION = explainer(BG_SCALED)
BG_EXPLANATION.feature_names = np.array(FEATURES)
```
###### scaled = ( raw_value - dataset_mean ) / dataset_sd
```{python}
from shiny import ui
# ── Row 1: three-column input layout ──
with ui.layout_columns(col_widths=[4, 4, 4], height="320px"):
with ui.card(full_screen=True):
ui.card_header("Student Profile")
ui.card_body(
ui.input_slider("age", "Age", min=18, max=25, value=21),
ui.input_select("gender", "Gender", choices=["Male", "Female"]),
ui.input_select("programme", "Programme", choices=PROGRAMMES)
)
with ui.card(full_screen=True):
ui.card_header("Academic Record")
ui.card_body(
ui.input_slider("attendance_pct", "Attendance %", min=40, max=100, value=85),
ui.input_slider("assignment_avg", "Assignment Avg", min=15, max=100, value=75),
ui.input_slider("quiz_avg", "Quiz Avg", min=10, max=100, value=70),
ui.input_slider("midterm_score", "Midterm Score", min=0, max=100, value=60),
ui.input_slider("previous_gpa", "Previous GPA", min=0.3, max=4.0, value=3.0, step=0.1)
)
with ui.card(full_screen=True):
ui.card_header("Habits & Circumstances")
ui.card_body(
ui.input_slider("study_hours_week", "Study Hours / Week", min=0, max=25, value=10, step=0.5),
ui.input_slider("absences", "Absences", min=0, max=13, value=2),
ui.input_switch("internet_access", "Internet Access", value=True),
ui.input_switch("extracurricular", "Extracurricular Activities", value=False)
)
# ── Row 2: single prediction text ──
with ui.layout_columns(col_widths=[12], height="150px"):
with ui.card(full_screen=True):
ui.card_header("Prediction Output")
ui.card_body(
ui.output_text("risk_summary")
)
# ── Row 3: SHAP waterfall full width ──
with ui.layout_columns(col_widths=[12], height="500px"):
with ui.card(full_screen=True):
ui.card_header("SHAP Waterfall — Individual Prediction Explanation")
ui.card_body(
ui.output_plot("risk_waterfall", height="420px")
)
# ── Row 4: SHAP beeswarm full width ──
with ui.layout_columns(col_widths=[12], height="500px"):
with ui.card(full_screen=True):
ui.card_header("SHAP Beeswarm — Global Feature Importance")
ui.card_body(
ui.output_plot("risk_beeswarm", height="420px")
)
# ── Row 3: batch CSV upload + downloads ──
with ui.layout_columns(col_widths=[6, 6], height="420px"):
with ui.card(full_screen=True):
ui.card_header("Batch Prediction — Upload CSV")
ui.card_body(
ui.input_file(
"csv_upload", "Upload CSV with student data",
accept=[".csv"],
multiple=False,
button_label="Choose file…",
placeholder="No file selected"
),
ui.output_text("batch_status"),
ui.output_table("batch_table")
)
with ui.card(full_screen=True):
ui.card_header("Download Reports")
ui.card_body(
ui.download_button("download_csv", "Download Batch Results (CSV)"),
ui.download_button("download_pdf", "Download Single-Input Report (PDF)"),
ui.output_text("download_status")
)
```
```{python}
#| output: false
from shiny import render, reactive
def build_features():
programme = input.programme()
engagement_score = (input.attendance_pct() + input.assignment_avg()) / 2.0
row = {
"age": input.age(),
"gender": GENDER_MAP[input.gender()],
"attendance_pct": input.attendance_pct(),
"assignment_avg": input.assignment_avg(),
"quiz_avg": input.quiz_avg(),
"midterm_score": input.midterm_score(),
"study_hours_week": input.study_hours_week(),
"previous_gpa": input.previous_gpa(),
"absences": input.absences(),
"internet_access": int(input.internet_access()),
"extracurricular": int(input.extracurricular()),
"prog_Computer Science": int(programme == "Computer Science"),
"prog_Data Science": int(programme == "Data Science"),
"prog_IT": int(programme == "IT"),
"prog_Software Engineering": int(programme == "Software Engineering"),
"engagement_score": engagement_score
}
return pd.DataFrame([row])[FEATURES]
def predict_single(X_raw):
X_scaled = scaler.transform(X_raw)
proba = float(model.predict_proba(X_scaled)[0, 1])
pred = 1 if proba >= THRESHOLD else 0
label = "At Risk" if pred == 1 else "Low Risk"
exp = explainer(X_scaled)
exp.feature_names = np.array(FEATURES)
return proba, pred, label, exp
@render.text
def risk_summary():
X = build_features()
proba, pred, label, exp = predict_single(X)
sv = exp.values[0]
top = pd.Series(sv, index=FEATURES).sort_values(ascending=False).head(3)
drivers = ", ".join([f"{name} ({val:+.3f})" for name, val in top.items()])
return (
f"Prediction: {label}\n"
f"Probability: {proba:.4f}\n"
f"Top 3 SHAP drivers: {drivers}"
)
@render.plot
def risk_waterfall():
X = build_features()
_, _, _, exp = predict_single(X)
plt.close("all")
shap.plots.waterfall(exp[0], show=False)
return plt.gcf()
@render.plot
def risk_beeswarm():
plt.close("all")
shap.plots.beeswarm(BG_EXPLANATION, show=False)
return plt.gcf()
@reactive.calc
def batch_results():
file_info = input.csv_upload()
if file_info is None:
return None
try:
df = pd.read_csv(file_info[0]["datapath"])
# Derived feature
if "engagement_score" not in df.columns:
df["engagement_score"] = (df["attendance_pct"] + df["assignment_avg"]) / 2.0
# Gender encoding — robust to strings or mixed types
if "gender" in df.columns:
df["gender"] = (
df["gender"]
.astype(str)
.str.strip()
.str.capitalize()
.map(GENDER_MAP)
.fillna(0)
.astype(int)
)
# Binary Yes/No fields (robust to StringDtype / object / bool)
binary_map = {"Yes": 1, "No": 0, "yes": 1, "no": 0, "True": 1, "False": 0, "1": 1, "0": 0}
for col in ["internet_access", "extracurricular"]:
if col in df.columns:
df[col] = df[col].astype(str).str.strip().map(binary_map).fillna(0).astype(int)
# Programme one-hot encoding using exact FEATURES names
if "programme" in df.columns:
df["programme"] = df["programme"].astype(str).str.strip()
for prog in PROGRAMMES:
feat_name = f"prog_{prog}"
if feat_name not in df.columns:
if "programme" in df.columns:
df[feat_name] = (df["programme"] == prog).astype(int)
else:
df[feat_name] = 0
# Ensure every model feature exists with numeric type
for col in FEATURES:
if col not in df.columns:
df[col] = 0
df[col] = pd.to_numeric(df[col], errors="coerce")
if df[FEATURES].isnull().any().any():
bad_cols = df[FEATURES].columns[df[FEATURES].isnull().any()].tolist()
return f"Error: missing or non-numeric values in columns {bad_cols}"
X = df[FEATURES]
X_scaled = scaler.transform(X)
probs = model.predict_proba(X_scaled)[:, 1]
preds = (probs >= THRESHOLD).astype(int)
out = df.copy()
out["risk_probability"] = probs
out["risk_label"] = np.where(preds == 1, "At Risk", "Low Risk")
return out
except Exception as e:
return f"Error: {str(e)}"
@render.text
def batch_status():
res = batch_results()
if res is None:
return "Upload a CSV file to run batch predictions."
if isinstance(res, str):
return res
return f"Loaded {len(res)} rows. Preview below."
@render.table
def batch_table():
res = batch_results()
if res is None or isinstance(res, str):
return None
priority = ["student_id", "risk_probability", "risk_label"]
display_cols = [c for c in priority if c in res.columns]
other_cols = [c for c in res.columns if c not in priority and c not in FEATURES[-4:]]
display_cols += other_cols[:5]
return res[display_cols].head(10)
@render.download(filename="batch_predictions.csv")
def download_csv():
res = batch_results()
if res is None or isinstance(res, str):
yield b"No data available. Upload a CSV first."
else:
yield res.to_csv(index=False).encode("utf-8")
@render.download(filename="risk_report.pdf")
def download_pdf():
X = build_features()
proba, _, label, exp = predict_single(X)
sv = exp.values[0]
top = pd.Series(sv, index=FEATURES).sort_values(ascending=False).head(3)
pdf_buffer = io.BytesIO()
with PdfPages(pdf_buffer) as pdf:
# Page 1: text summary
fig, ax = plt.subplots(figsize=(8.27, 11.69))
ax.axis("off")
lines = [
"Student Academic Risk Report",
"",
f"Prediction: {label}",
f"Probability: {proba:.4f}",
"",
"Top 3 SHAP drivers:"
]
for name, val in top.items():
lines.append(f" {name}: {val:+.3f}")
lines += ["", "Input Features:"]
for feat, val in X.iloc[0].items():
lines.append(f" {feat}: {val}")
ax.text(
0.1, 0.95, "\n".join(lines),
transform=ax.transAxes, fontsize=12, verticalalignment="top"
)
pdf.savefig(fig, bbox_inches="tight")
plt.close(fig)
# Page 2: SHAP waterfall
plt.close("all")
shap.plots.waterfall(exp[0], show=False)
pdf.savefig(plt.gcf(), bbox_inches="tight")
plt.close("all")
# Page 3: SHAP beeswarm
plt.close("all")
shap.plots.beeswarm(BG_EXPLANATION, show=False)
pdf.savefig(plt.gcf(), bbox_inches="tight")
plt.close("all")
pdf_buffer.seek(0)
yield pdf_buffer.getvalue()
@render.text
def download_status():
return "Ready. Use the buttons above to download reports."
```