Repository navigation
Expand file tree
/
Copy pathP01.qmd
More file actions
1162 lines (855 loc) · 43.6 KB
/
Copy pathP01.qmd
File metadata and controls
1162 lines (855 loc) · 43.6 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "DATA ANALYSIS REPORT "
author: "GROUP 01"
date: "2026-08-21"
abstract: |
This study applies a complete data science pipeline to predict academic risk among university students. Using a dataset of 12,084 records, we investigate data quality issues, apply justified preprocessing techniques, and compare four machine learning models: Logistic Regression, Random Forest, Gradient Boosting, and XGBoost. Due to severe class imbalance (~85.6% Not At Risk), we prioritise recall and ROC-AUC over accuracy. Our findings indicate that while traditional models struggle to identify at-risk students, XGBoost with class balancing and Youden-index threshold tuning significantly improves recall to 63.5%. Feature importance analysis reveals that a newly engineered variable, `engagement_score` (combining attendance and assignment averages), is the strongest predictor of academic risk, followed by midterm scores.
format:
html: default
pdf: default
bibliography: references.bib
csl: https://www.zotero.org/styles/apa
css: styles.css
---
# **DATA ANALYSIS MINI PROJECT: STUDENT ACADEMIC RISK**
:::: {.callout-note appearance="simple" icon="false"}
## **Project Brief**
**Domain:** Higher Education / Student Performance
**Task:** Binary Classification
**Target Variable:** `academic_risk` (At Risk vs. Not At Risk)
**Primary Project Question:** Predict whether a student is academically *At Risk* or *Not At Risk*?
::::
## **1. BUSINESS UNDERSTANDING**
### Domain & Problem Context
In higher education, identifying students at risk of academic failure before it is too late is a critical challenge. Late identification often leads to dropped courses, poor graduation rates, and reduced student morale. By leveraging historical student data, universities can build predictive models to flag "At Risk" students early in the semester, allowing academic advisors to intervene proactively rather than reactively.
### Project Objective
The primary objective of this project is to build a predictive model that classifies whether a student is academically **"At Risk"** or **"Not At Risk"** based on their demographic, academic, and behavioural data.
### Stakeholders & Value
- **Who could use the findings?** Academic advisors, student affairs departments, and university retention teams.
- **What value does the analysis provide?** It enables a data-driven, early-warning system. By knowing *which* factors drive risk and *who* is most likely to struggle, advisors can allocate limited resources to the students who need help the most.
### Supporting Research Questions
To guide our analysis, we formulated three supporting questions:
1. Which features (attendance, midterm, GPA) are the strongest predictors of academic risk?
2. Does programme type influence academic risk?
3. How does study hours per week relate to being at risk?
## **PHASE 1: SETUP & LOAD THE DATA**
### **IMPORT ALL LIBARIES**
```{python}
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import(
accuracy_score, precision_score, recall_score, f1_score,
confusion_matrix, classification_report, roc_auc_score, roc_curve
)
import warnings
warnings.filterwarnings('ignore')
# we need to set the style
sns.set_style('whitegrid')
RANDOM_STATE = 42
# load datasets
df = pd.read_csv('data/group01_student_performance_classification.csv')
df_raw = df.copy()
print("Shape:", df.shape)
print(df.head())
```
##### All data manipulation is performed using pandas [@pandas], while machine learning models are built with scikit-learn [@sklearn]. Visualisations use matplotlib [@matplotlib] and seaborn [@seaborn].
### **SAVE COPY AS ORIGINAL**
```{python}
df.to_csv('P01_data_original.csv', index=False)
print("Original dataset saved")
```
## **PHASE 2: DATA UNDERSTANDING**
### **BASIC STRUCTURE & MISSING VALUES**
```{python}
print(df.dtypes)
print("\nMissing Values:")
print(df.isnull().sum())
print("\nMissing Values (%):")
print((df.isnull().sum() / len(df) * 100).round(2))
print("\nDuplicate Rows:", df.duplicated().sum())
```
### **TARGET DISTRIBUTION**
```{python}
print(df['academic_risk'].value_counts())
print("\nPercentages:")
print(df['academic_risk'].value_counts(normalize=True) * 100)
# normalize true here means ?
# it means that : shows what fraction from 0 to 1 of students are each category
```
### **NUMERICAL SUMMARY**
```{python}
numeric_cols = df.select_dtypes(include=[np.number]).columns
print(df[numeric_cols].describe().round(2))
```
### **CATEGORICAL SUMMARY**
```{python}
cat_cols = ['gender', 'programme', 'internet_access', 'extracurricular']
for col in cat_cols:
print(f"\n-- {col} ---")
print(df[col].value_counts(dropna=False).head(10))
```
### **DATA QUALITY ISSUES**
```{python}
print("Gender unique values:", df['gender'].unique())
print("\nProgramme missing: ", df['programme'].isnull().sum())
print("Midterm missing:", df['midterm_score'].isnull().sum())
print("Absence missing:", df['absences'].isnull().sum())
print("Internet access missig", df['internet_access'].isnull().sum())
```
## **VISUALIZATION**
#### V1: TARGET DISTRIBUTION
```{python}
plt.figure(figsize=(6, 4))
sns.countplot(data=df, x='academic_risk', palette=['seagreen', 'red'])
plt.title('Distribution of Academic Risk')
plt.xlabel('Academic Risk')
plt.ylabel('Count')
plt.show()
```
> "The dataset is imbalanced: approximately around **85.6% "Not At Risk"** vs **~14.4% "At Risk"**. This means accuracy alone is misleading. Hence we will use f1-Score, recall and ROC-AUC."
#### V2: ATTENDANCE VS RISK
```{python}
plt.figure(figsize=(8,5))
sns.boxplot(data=df, x='academic_risk', y='attendance_pct', palette=['seagreen', 'red'])
plt.title('Attendance % by Academic Risk')
plt.show()
```
#### V3: MIDTERM SCORE VS RISK
```{python}
plt.figure(figsize=(8,5))
sns.boxplot(data=df, x='academic_risk', y='midterm_score', palette=['seagreen', 'red'])
plt.title('Midterm Score by Academic risk')
plt.show()
```
## **PHASE 3: DATA PREPROCESING (CLEANING)**
### STEP 1: HANDLE DUPLICATES
```{python}
# shows the original for we do the deduplication operation
print("Before Dedup Operations:", df.shape)
df = df.drop_duplicates()
print("After Dedup Operations:", df.shape)
```
### STEP 2: FIX GENDER INCONSISTENCIES
```{python}
# standardize gender values
df['gender'] = df['gender'].replace({
'female': 'Female',
'M': 'Male',
'Male': 'Male',
'Female': 'Female'
})
print("\nGender values now:", df['gender'].unique())
```
### STEP 3: HANDLE MISSING VALUES
> We actually got 2 options here which is **drop** or **impute** the missing values 😎
###### first we need to investigate, how missing values are distributed, are they random or systematic ?
```{python}
# check if missing values are they the same rows ??
missing_mask = df[['programme', 'midterm_score', 'absences', 'internet_access']].isnull().any(axis=1)
print("Rows with ANY missing value:", missing_mask.sum())
# ====== How many missing values does each affected row have?
missing_counts = df[['programme', 'midterm_score', 'absences', 'internet_access']].isnull().sum(axis=1)
print("Distribution of missing values per row:")
print(missing_counts[missing_counts > 0].value_counts().sort_index())
# ====== check if missingness relates to the target ======
print("\nMissing values by academic_risk:")
print(df[missing_mask]['academic_risk'].value_counts())
```
###### *706 here means that any rows that have at least one missing values are counted*
###### "Missing values here occur mostly in isolation (692 rows missing 1 value, 14 rows missing 2 values). This suggests that missing data is scattered and largely random, rather than caused by a systematic, and this support our decision of using imputation to preserve all records rather than dropping them"
### STEP 4: IMPUTE THE MISSING VALUES
#### 4.01 CHECK THE SKEWNESS (TO JUSTIFY WETHER TO USE MEDIAN OR MEAN)
```{python}
# check the skewness to justify median vs mean for numeric columns
print("Skewness:")
for col in ['midterm_score', 'absences', 'attendance_pct', 'previous_gpa', 'assignment_avg', 'quiz_avg']:
print(f" {col}: {df[col].skew():.3f}")
# plotting the skewness using plotly and seaborn
sns.set_style("whitegrid")
# creating the 2 x 3 grid of subplots
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
# flatten the axes for easy iteration
axes = axes.flatten()
# plot each columns
for i, col in enumerate(['midterm_score', 'absences', 'attendance_pct', 'previous_gpa', 'assignment_avg', 'quiz_avg']):
sns.histplot(df[col], kde=True, ax=axes[i], bins=20, color='skyblue')
axes[i].set_title(f'{col}\nSkewness: {df[col].skew():.3f}')
axes[i].set_xlabel('')
plt.tight_layout()
plt.show()
```
###### The Simple Rule
> look at the shape of the histogram:
> - **Symmetrical bell shape -> mean**
> - **long tail at one side -> median**
#### 4.02 IMPUTE CATEGORICAL WITH ( MODE )
```{python}
# Categorical: fill with mode (most common value)
for col in ['programme', 'internet_access']:
mode_val = df[col].mode()[0]
df[col].fillna(mode_val, inplace=True)
# inplace=true means that it will change the dr directly nnot creating another df for this operations
print(f" {col} -> filled with mode: {mode_val}")
```
#### 4.03 IMPUTE NUMERICAL WITH ( MEDIAN )
```{python}
# for Numeric: fill with median (robust to outliers/skew)
for col in ['midterm_score', 'absences']:
median_val = df[col].median()
df[col].fillna(median_val, inplace=True)
print(f" {col} -> filled with median: {median_val:.2f}")
```
#### 4.04 VERIFY NO MISSING VALUES REMAINS
```{python}
print(f"Remaining missing values")
print(df.isnull().sum())
```
> "During the imputation, also we discovered that some "missing" values were stored as empty strings ('') rater than NaN, which is why fillna() initially had no effect. Empty strings were first converted to NaN using df.replace('', np.nan) before applying median/mode imputation"
#### 4.05 CONVERTING EMPTY STRINGS TO NaN first, THEN we imputes:
```{python}
# step 1: convert empty strings to NaN
df = df.replace('', np.nan)
# step 2: Re-check the missing values
print("Missing after converting '' to NaN")
print(df.isnull().sum())
```
#### 4.06 RUN IMPUTATION AGAIN
```{python}
# Categorical: fill with mode
for col in ['programme', 'internet_access']:
mode_val = df[col].mode()[0]
df[col].fillna(mode_val, inplace=True)
print(f" {col} -> filled with mode: {mode_val}")
# for Numeric fill with median
for col in ['midterm_score', 'absences']:
median_val = df[col].median()
df[col].fillna(median_val, inplace=True)
print(f" {col} -> filled with median: {median_val}")
```
#### 4.07 VERIFY IT AGAIN
```{python}
print("Remaining missing values:")
print(df.isnull().sum())
```
> Still getting missing values
#### 4.08 RUN DIAGNOSES OF WHAT ACTUALLY MISSING VALUES IS ?
```{python}
# Diagnoses: what are these missing values really
for col in ['programme', 'midterm_score', 'absences', 'internet_access']:
nan_count = df[col].isnull().sum()
empty_count = (df[col] == '').sum()
space_count = df[col].astype(str).str.strip().eq('').sum()
print(f"\n{col}: NaN={nan_count}, empty=''{empty_count}, whitespace={space_count}")
print(f" dtype: {df[col].dtype}")
# show the actual weird values
if nan_count > 0:
print(" Sample of missing values")
print(df.loc[df[col].isnull(), col].head(5).tolist())
```
> Still got NaN values
#### 4.09 USE ASSIGNMENT INSTEAD OF APPROACH
```{python}
# Categorical: Mode
for col in ['programme', 'internet_access']:
mode_val = df[col].mode()[0]
df[col] = df[col].fillna(mode_val) # we use assignment NOT inplace
print(f" {col} -> filled with mode: {mode_val}")
# Numerical: Median
for col in ['midterm_score', 'absences']:
median_val = df[col].median()
df[col] = df[col].fillna(median_val)
print(f" {col} -> filled with median: {median_val}")
```
#### 4.10 CONFIRMATION AGAIN
```{python}
print("Remaining missing values:")
print(df.isnull().sum())
```
###### Why this happening ?
###### *in pandas 3.0, df.[col].fillna(..., inplace=True) does not modify the original DataFrame due to Copy-on-Write semantics - df[col] returns a copy.This is why df.isnull().sum() still showed 180 missing values after the first and second attempt. Therefore we used explicit assignment df[col] = df[col].fillna() to correctly updated the data*
#### 4.11 USING VISUALIZATION TO SHOWS THAT OUR IMPUTATIONS DIDN'T DISTORT THE DATA DISTRIBUTION
```{python}
sns.set_style("whitegrid")
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
# ====== Midterm Score =======
sns.histplot(df['midterm_score'], kde=True, ax=axes[0], bins=20, color='skyblue')
axes[0].axvline(df['midterm_score'].median(), color='red', linestyle='--',
label=f"Median: {df['midterm_score'].median():.1f}")
axes[0].set_title('Midterm Score (after imputation)')
axes[0].legend()
# ====== Absences ======
sns.histplot(df['absences'], kde=True, ax=axes[1], bins=20, color='orange')
axes[1].axvline(df['absences'].median(), color='red', linestyle='--',
label=f"Median: {df['absences'].median():.1f}")
axes[1].set_title("Absences (after imputation)")
axes[1].legend()
plt.tight_layout()
plt.show()
#
```
> The distribution after imputation remain visually unchanged
### STEP 5: ENCODING CATEGORICAL VARIABLES
Most machine-learning algorithms require numerical input, so categorical variables must be transformed before model training [@hastie2009]. Binary variables (Yes/No, Male/Female) are mapped to 0/1, while multi-category `programme` variable is one-hot encoded to avoid introducing a false ordinal relationship [@sklearn_preprocessing]
#### 5.1 ENCODE BINARY COLUMNS (0/1)
```{python}
df['gender'] = df['gender'].map({'Male': 0, 'Female': 1})
df['internet_access'] = df['internet_access'].map({'No': 0, 'Yes': 0})
df['extracurricular'] = df['extracurricular'].map({'No': 0, 'Yes': 1})
df['academic_risk'] = df['academic_risk'].map({'Not At Risk': 0, 'At Risk': 1})
# for confirmation
print("Binary columns encoded")
df[['gender', 'internet_access', 'extracurricular', 'academic_risk']].head()
```
#### 5.2 ONE-HOT ENCODE 'programme'
```{python}
# BEFORE encoding
print("BEFORE one-hot encoding:")
print(df_raw[['student_id', 'programme']].head(3))
# performing one-hot encoding
df = pd.get_dummies(df, columns=['programme'], prefix='prog')
# Show the result
prog_cols = [c for c in df.columns if c.startswith('prog_')]
df[prog_cols] = df[prog_cols].astype(int)
print("One-hot encoded columns:", prog_cols)
print("\nFirst 10 rows (1 = student's programme):")
print(df[prog_cols].head(10))
```
> **"One-hot encoding expanded `programme` into 4 binary indicator columns. Each row has a 1 in exactly one column and 0 elsewhere, treating the categories as independent rather than imposing a false ordering [@hastie2009]."**
### STEP 6: SAVED CLEANED DATASET
```{python}
# Feature Engineering: Create an 'engagement_score' (average of attendance and assignment)
df['engagement_score'] = (df['attendance_pct'] + df['assignment_avg']) / 2
print("Created 'engagement_score' feature.")
# save cleaned dataset
df.to_csv('P01_data_cleaned.csv', index=False)
print("Cleaned dataset saved. Shape:", df.shape)
```
### STEP 7: TRAIN/TEST SPLIT
The data is split into training (80%) and testing (20%) sets **before** any scaling or model fitting to prevent **data leakage** [@hastie2009]. The test set shall remains completely unseen during training so that evaluation reflects real-world generalization performance. Learning the parameters of a prediction function and testing it on the same data is a methodology mistake: a model that would just repeat the labels of the sampes that it has just seen would have a perfect score but would fail to predict anything useful on yet-unseen data. This situation called **overfitting**. To avoid it, it is common practice when performing a (supervised) machine learning experiment to hold out part of the available data as a test set X_test, y_test [@sklearn_model_selection]. Here is a flowchart of typical cross validation workflow in model training.
{ width="400px" }
```{python}
# seperate features and target
X = df.drop(columns=['student_id', 'academic_risk'])
y = df['academic_risk']
# split
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.2,
# we using Hold Out Method to train split dataset
random_state=RANDOM_STATE,
stratify=y
# this stratify will split forces the 85.6% / 14.4% ratio to be perfectly preserved set in both sets
)
print("Training set:", X_train.shape)
print("Test set:", X_test.shape)
print("\nClass balance in test set:")
# normalize = count/total -> converting count to proportion
print(y_test.value_counts(normalize=True).round(3))
```
## **PHASE 4: MODELLING**
### STEP 1: SCALE NUMERICAL FEATURES
Scaling standardize numerical features to zero mean and unit variance so feautres with larger magnitudes like attendance_pct 0-100 do not dominate features with smaller ranges like previous_gpa 0-4 [@sklearn_preprocessing].
```{python}
#| label: scaling
#| fig-cap: "Feature Scaling Implementation"
from sklearn.preprocessing import StandardScaler
# define the StandardScaler
scaler = StandardScaler()
# fit only on training data, then transform both sets (prevents leakage)
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print("Training shape (scaled):", X_train_scaled.shape)
print("Test shape (scaled):", X_test_scaled.shape)
```
:::: callout-tip
#### **The Rule**
> The Scaler is **fit on the training set only** (`fit_transform`) and then
> applied to the test set using `transform`. This prevents the test data from ?
> leaking information into the model, which would inflate performance
> unrealistically [@hastie2009].
::::
### STEP 1.5: METRICS & CONFUSION MATRIX EXPLAINED
> For binary classification, we evaluate models using several metrics, because accuracy alone is just misleading when classes are imbalanced [@hastie2009].
#### **Confusion Matrix**
- **TN** : correctly predicted "Not At Risk"
- **FP** : wrongly flagged as "At Risk" (false alarm)
- **FN** : missed At Risk student (most costly error)
- **TP** : correctly identified "At Risk"
#### **Key Metrics**
| Metric | Formula | Meaning | Why it matters here |
|--------|---------|---------|---------------------|
| **Accuracy** | (TP + TN) / Total | % of all predictions correct | Misleading for imbalanced data |
| **Precision** | TP / (TP + FP) | Of students flagged "At Risk", how many are truly at risk | Avoids false alarms |
| **Recall** | TP / (TP + FN) | Of actual at risk students, how many were caught | **Most important** — don't miss at risk students |
| **F1-Score** | 2·(P·R) / (P + R) | Harmonic mean of precision & recall | Single balanced summary |
| **ROC-AUC** | Area under ROC curve | Model's ability to separate the two classes | Overall discrimination, threshold independent |
### STEP 2: BASELINE MODEL - LOGISTIC REGRESSION
Logistic regression is a simple, interpretable linear model that serves as our baseline. It predicrs the probability of a student being "At Risk" [@sklearn].
```{python}
#| label: logistic regression
#| fig-cap: "Logistic Regression Base line model"
from sklearn.linear_model import LogisticRegression
# Train baseline model
lr = LogisticRegression(max_iter=1000, random_state=RANDOM_STATE)
lr.fit(X_train_scaled, y_train)
# we predict on test set
y_pred_lr = lr.predict(X_test_scaled)
y_proba_lr = lr.predict_proba(X_test_scaled)[:, 1]
# evaluate with FULL metrics
print("=" * 50)
print("LOGISTIC REGRESSION (BASELINE)")
print("=" * 50)
print(f"Accuracy : {accuracy_score(y_test, y_pred_lr):.4f}")
print(f"Precision: {precision_score(y_test, y_pred_lr):.4f}")
print(f"Recall : {recall_score(y_test, y_pred_lr):.4f}")
print(f"F1-Score : {f1_score(y_test, y_pred_lr):.4f}")
print(f"ROC-AUC : {roc_auc_score(y_test, y_proba_lr):.4f}")
# Confusion matrix
print("\nConfusion Matrix:")
cm = confusion_matrix(y_test, y_pred_lr)
print(cm)
print(f"\n True Negatives (TN): {cm[0,0]}")
print(f" False Positives (FP): {cm[0,1]}")
print(f" False Negatives (FN): {cm[1,0]}")
print(f" True Positives (TP): {cm[1,1]}")
# Detailed classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred_lr, target_names=['Not At Risk', 'At Risk']))
```
#### Result Summary
| Metric | Value | Interpretation |
|--------|-------|----------------|
| Accuracy | 0.8538 | High, but misleading due to class imbalance |
| Precision | 0.4250 | Of flagged students, 42.5% are truly "At Risk" |
| **Recall** | **0.0493** | **Only 4.9% of "At Risk" students were caught** |
| F1-Score | 0.0883 | Very poor model barely learns the minority class |
| ROC-AUC | 0.7332 | Model *can* separate classes, but threshold is wrong |
#### Confusion Matrix
| | Predicted Not At Risk | Predicted At Risk |
|---|---|---|
| **Actual Not At Risk** | 2033 (TN) | 23 (FP) |
| **Actual At Risk** | 328 (FN) Alert ! | 17 (TP) |
#### Critical Insight
> The baseline achieves 85.4% accuracy but a recall of only **4.9%**, identifying just 17 of 345 truly at-risk students. This is the classic imbalanced-classification pitfall, the model defaults to the majority class **("Not At Risk")** and achieves high accuracy while learning almost nothing about **("At Risk")** students. The 328 false negatives are the most .This clearly shows that we have to do class balancing and threshold tuning in the next models.
### STEP 3: RANDOM FOREST MODEL
Random Forest is an ensemble of decision trees that combines many trees to reduce overfitting and improve generalization [@random_forest]. We use `class_weight= 'balanced'` to counteract the class imbalance by giving more weight to minority class which is ("At Risk")
```{python}
#| label: random forest
#| fig-cap: "Random Forest with class balancing"
from sklearn.ensemble import RandomForestClassifier
# random forest with balanced class weight
rf = RandomForestClassifier(
n_estimators=200,
class_weight='balanced',
random_state=RANDOM_STATE,
)
rf.fit(X_train_scaled, y_train)
# Predicting
y_pred_rf = rf.predict(X_test_scaled)
y_proba_rf = rf.predict_proba(X_test_scaled)[:, 1]
# Full Metrics of this Training
print("=" * 50)
print("RANDOM FOREST (class_weight='balanced')")
print("=" * 50)
print(f"Accuracy: {accuracy_score(y_test, y_pred_rf):.4f}")
print(f"Precision: {precision_score(y_test, y_pred_rf):.4f}")
print(f"Recall : {recall_score(y_test, y_pred_rf):.4f}")
print(f"F1-Score : {f1_score(y_test, y_pred_rf):.4f}")
print(f"ROC-AUC : {roc_auc_score(y_test, y_proba_rf):.4f}")
# Confusion matrix
print("\nConfusion Matrix:")
cm = confusion_matrix(y_test, y_pred_rf)
print(cm)
print(f"\n TN: {cm[0,0]} FP: {cm[0,1]}")
print(f" FN: {cm[1,0]} TP: {cm[1,1]}")
# Classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred_rf, target_names=['Not At Risk', 'At Risk']))
```
#### Key Metrics
| Metric | Value | Interpretation |
|--------|-------|----------------|
| Accuracy | 0.8401 | Remains high, but continues to be misleading due to class imbalance |
| Precision | 0.3655 | 36.6% of students flagged as "At Risk" are actually at risk—3x improvement over baseline (12.5%)|
| **Recall** | **0.1536** | **15.4% of truly At Risk students were caught approximately 3x improvement over baseline (4.9%)** |
| F1-Score | 0.2163 | Balanced measure showing modest improvement|
| ROC-AUC | 0.6935 | Moderate discriminative ability (below the 0.70 threshold)|
#### Critical Insight
> The Random Forest model with class balancing achieves a 3-fold improvement in recall over the baseline (15.4% vs 4.9%), but this remains insufficient for practical deployment as a standalone screening tool. The model's limited performance (ROC-AUC = 0.6935) and high false negative rate (84.6%) suggest that the available features capture only a portion of the factors contributing to academic risk. Future work should focus on expanding feature sets, refining the risk definition, and implementing human-in-the-loop review processes.
### STEP 4: GRADIENT BOOSTING
> Gradient Boosting is an ensemble method that builds trees sequentially, with each new tree correcting the erros of the previous ones. It is often the strongest performer on structured/tabular data [@sklearn].
```{python}
#| label: gradient boosting
from sklearn.ensemble import GradientBoostingClassifier
# Gradient Boosting
gb = GradientBoostingClassifier(
n_estimators=200,
learning_rate=0.1,
max_depth=3,
random_state=RANDOM_STATE
)
gb.fit(X_train_scaled, y_train)
# Predict
y_pred_gb = gb.predict(X_test_scaled)
y_proba_gb = gb.predict_proba(X_test_scaled)[:, 1]
# Full metrics
print("=" * 50)
print("GRADIENT BOOSTING")
print("=" * 50)
print(f"Accuracy : {accuracy_score(y_test, y_pred_gb):.4f}")
print(f"Precision: {precision_score(y_test, y_pred_gb):.4f}")
print(f"Recall : {recall_score(y_test, y_pred_gb):.4f}")
print(f"F1-Score : {f1_score(y_test, y_pred_gb):.4f}")
print(f"ROC-AUC : {roc_auc_score(y_test, y_proba_gb):.4f}")
# Confusion matrix
print("\nConfusion Matrix:")
cm = confusion_matrix(y_test, y_pred_gb)
print(cm)
print(f"\n TN: {cm[0,0]} FP: {cm[0,1]}")
print(f" FN: {cm[1,0]} TP: {cm[1,1]}")
# Classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred_gb, target_names=['Not At Risk', 'At Risk']))
```
#### Critical Insight
> The Gradient Boosting model achieves 84.6% accuracy but a recall of only 7.0%, identifying just 24 of 345 truly at-risk students while missing 321 (93.0%)—the worst performance among all models tested. Despite having a decent ROC-AUC of 0.7110, the model fails to translate this into meaningful recall. This poor performance is primarily due to the absence of built-in class balancing mechanisms. Unlike Random Forest with `class_weight='balanced'` (15.4% recall), vanilla Gradient Boosting defaults to the majority class, achieving high accuracy while learning almost nothing about "At Risk" students. This clearly demonstrates that explicit class balancing is essential for this problem, which will be addressed in the next step using XGBoost with `scale_pos_weight`.
### STEP 5: XGBoost
XGBoost (eXtreme Gradient Boosting) is an optimised gradient boosting implementation that adds regularisation to reduce overfitting and is widely regarded as one of the strongest models for structured/tabular data [@chen2016xgboost]. To handle the class imbalance, we set `scale_pos_weight` proportional to the negative to positive class ratio, which up weights the minority ("At Risk") class during training.
```{python}
#| label: XGBoost
import xgboost as xgb
# first we need to compute the scale_pos_weight (negatives / positives ) to balance classes
scale = (y_train == 0).sum() / (y_train == 1).sum()
print(f"scale_pos_weight: {scale:.2f}")
# lets train the XGBoost
xgb_model = xgb.XGBClassifier(
n_estimators=200,
learning_rate=0.1,
max_depth=5,
scale_pos_weight=scale,
random_state=RANDOM_STATE,
eval_metric='logloss'
)
# we must fit our model first to predict
xgb_model.fit(X_train_scaled, y_train)
# predicting....
y_pred_xgb = xgb_model.predict(X_test_scaled)
y_proba_xgb = xgb_model.predict_proba(X_test_scaled)[:, 1]
# Full metrics
print("=" * 50)
print("XGBOOST (scale_pos_weight=balanced)")
print("=" * 50)
print(f"Accuracy : {accuracy_score(y_test, y_pred_xgb):.4f}")
print(f"Precision: {precision_score(y_test, y_pred_xgb):.4f}")
print(f"Recall : {recall_score(y_test, y_pred_xgb):.4f}")
print(f"F1-Score : {f1_score(y_test, y_pred_xgb):.4f}")
print(f"ROC-AUC : {roc_auc_score(y_test, y_proba_xgb):.4f}")
# Confusion matrix
print("\nConfusion Matrix:")
cm = confusion_matrix(y_test, y_pred_xgb)
print(cm)
print(f"\n TN: {cm[0,0]} FP: {cm[0,1]}")
print(f" FN: {cm[1,0]} TP: {cm[1,1]}")
# Classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred_xgb, target_names=['Not At Risk', 'At Risk']))
```
> `scale_post_weight` is XGBoost's built in mechanism for imbalanced data.
> Setting it to `(negatives / positives)` makes the model treat each at risk
> example as if it appeared multiple times, counteracting the dominance of the "Not At Risk" majority class [@chen2016xgboost].
### STEP 6: MODEL COMPARISON TABLE
```{python}
#| label: Collect All result into one comparison table
# collect all results into one comparison table
results = pd.DataFrame({
'Model': ['Logistic Regression', 'Random Forest', 'Gradient Boosting', 'XGBoost'],
'Accuracy': [
accuracy_score(y_test, y_pred_lr),
accuracy_score(y_test, y_pred_rf),
accuracy_score(y_test, y_pred_gb),
accuracy_score(y_test, y_pred_xgb),
],
'Precision': [
precision_score(y_test, y_pred_lr),
precision_score(y_test, y_pred_rf),
precision_score(y_test, y_pred_gb),
precision_score(y_test, y_pred_xgb),
],
'Recall': [
recall_score(y_test, y_pred_lr),
recall_score(y_test, y_pred_rf),
recall_score(y_test, y_pred_gb),
recall_score(y_test, y_pred_xgb),
],
'F1-Score': [
f1_score(y_test, y_pred_lr),
f1_score(y_test, y_pred_rf),
f1_score(y_test, y_pred_gb),
f1_score(y_test, y_pred_xgb),
],
'ROC-AUC': [
roc_auc_score(y_test, y_proba_lr),
roc_auc_score(y_test, y_proba_rf),
roc_auc_score(y_test, y_proba_gb),
roc_auc_score(y_test, y_proba_xgb),
],
})
results.round(4)
```
### STEP 7: ROC CURVE : SHOWS ALL MODELS ON ONE PLOT
*ROC curve - graphical plot that shows how your model can distinguish between two classes (positive and negative) across all possible threshold.*
```{python}
#| label: ROC curves
# ROC curves for all models
plt.figure(figsize=(8, 6))
for name, proba in [('Logistic Regression', y_proba_lr),
('Random Forest', y_proba_rf),
('Gradient Boosting', y_proba_gb),
('XGBoost ', y_proba_xgb)
]:
fpr, tpr, _ = roc_curve(y_test, proba)
auc = roc_auc_score(y_test, proba)
plt.plot(fpr, tpr, label=f'{name} (AUC={auc:.3f})')
plt.plot([0, 1], [0, 1], 'k--', label='Random (AUC=0.5)')
plt.xlabel('False Positive Rate')
plt.ylabel('True Postive Rate (Recall)')
plt.title('ROC Curves - Model Comparison')
plt.legend()
plt.show()
```
#### **The Recall-Precision Trade Off**
> **XGBoost** achieves the highest recall by accepting more false positives:
>
> - Recall: 44.4% -> 153 At Risk students caught (best)
>
> - Precision: 24.9% -> 1 in 4 flagged students are actually at risk
>
> - False Positives: 462 students incorrectly flagged (22.5% of Not At Risk)
>
> - False Negatives: 192 At Risk students missed (55.6% best but still high)
#### **Interpreting ROC-AUC**
The ROC-AUC value reflects a model's ability to distinguish between the two classes. An AUC of 0.5 indicates no better than random guessing, while 1.0 indicates perfect discrimination [@corbacioglu2023roc]. In diagnostic accuracy studies, AUC values above 0.8 are generally considered as clinically useful, while values below 0.80 are of limited clinical utility [@corbacioglu2023roc].
In our case, the models achieve ROC-AUC values between 0.69 and 0.73, indicating **moderate but very limited discriminative ability**. This align with our finding that the available features are only moderate predictors of academic risk.
Every model struggles with recall. It's not code bug but this shows that we have issue with data property.
#### **Why XGBoost Winning While Others Failed**
| Factor | Interpretation |
|--------|-------|
| `scale_pos_weight=5.96` | Explicitly up-weights minority class examples, forcing the model to focus on "At Risk" students |
| Built in Regularization | Prevents overfitting to the majority class|
| Sequential Learning | Each tree corrects previous errors, but now errors on both classes are weighted appropriately |
| Gradient Based Optimization | More efficient than Random Forest's bagging approach for imbalanced data|
### STEP 8: IMPROVING RECALL AS WE CAN: BY USING "YOUDEN INDEX" THRESHOLD TUNING ON XGBOOST
> To select an optimal decision threshold, we use the **Youden Index**, which maximises (sensitivity + specificity - 1), balancing recall ad precision [@corbacioglu2023roc].
#### **WHAT IS YOUDEN INDEX ?**
> **Youden's Index (J)** = Sensitivity + Specificity - 1
Where:
- **Sensitivity** = Recall = TP / (TP + FN)
- **Specificity** = TN / (TN + FP)
The index ranges from 0 to 1, where:
- J = 1 -> Perfect classification (no errors)
- J = 0 -> No discriminative ability (random guessing)
> The **The optimal threshold** is the one that maximizes Youden's Index, balancing the trade-off between catching At Risk students (sensitivity) and avoiding false alarms (specificity).
```{python}
#| label: Youden Index
from sklearn.metrics import roc_curve
# Youden Index on XGBoost
fpr, tpr, threshold = roc_curve(y_test, y_proba_xgb)
youden_j = tpr - fpr
optimal_idx = np.argmax(youden_j)
optimal_threshold = threshold[optimal_idx]
print(f"Optimal threshold (Youden Index): {optimal_threshold:.4f}")
print(f" Sensitivity (Recall): {tpr[optimal_idx]:.4f}")
print(f" Specificity: {1 - fpr[optimal_idx]:.4f}")
# applying the optimal threshold to threshold
y_pred_optimal = (y_proba_xgb >= optimal_threshold).astype(int)
print("\n=== XGBOOST with Youden-optimised threshold ===")
print(f"Accuracy : {accuracy_score(y_test, y_pred_optimal):.4f}")
print(f"Precision: {precision_score(y_test, y_pred_optimal):.4f}")
print(f"Recall : {recall_score(y_test, y_pred_optimal):.4f}")
print(f"F1-Score : {f1_score(y_test, y_pred_optimal):.4f}")
print("\nConfusion Matrix:")
cm = confusion_matrix(y_test, y_pred_optimal)
print(cm)
print(f"\n TN: {cm[0,0]} FP: {cm[0,1]}")
print(f" FN: {cm[1,0]} TP: {cm[1,1]}")
```
#### Result Summary
| Metric | Default (0.5) | Youden-Optimised | Change |
|--------|--------------|------------------|--------|
| **Recall** | 0.4435 | **0.6348** | **+19.1%** |
| Precision | 0.2488 | 0.2221 | -2.7% |
| Accuracy | 0.7276 | 0.6281 | -9.9% |
| At-Risk Caught | 153 / 345 | **219 / 345** | +66 more students |
#### Critical Insight
> By lowering the decision threshold from the default 0.5 to the Youden-optimal value (~0.31), recall jumps to 63.5% which is huge improvement, meaning the model now catches 219 out of 345 At Risk students (compared to just 17 in the baseline).
>
> The trade off is a high false positive rate (767 students wrongly flagged).
> However, in the academic advising context,
> this is an acceptable cost:
> a false positive merely triggers an advisory check,
> whereas a false negative means a student misses out
> on critical intervention.
> This prioritisation of recall is standard practice in imbalanced domains where the minority
> class represents a **high cost** negative outcome [@corbacioglu2023roc].
### STEP 9: PROBABILITY SMOOTHING (CALIBRATION)
> To ensure our model's predicted probabilities reflect true real-world likelihoods, we apply probabiliy calibration. Tree based models like often output overconfident or skewed probabilites. We use `CalibratedClassifierCV` with isotonic regression to smooth these probabilities, making the model's confidence scores more reliable for decision-making [@sklearn].
```{python}
#| lable: probability calibration
#| fig-cap: "Probability Calibration Curve"
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
# Apply the Isotonic Smoothing to the XGBoost model (cv=5 cross-validates the calibration)
calibrated_xgb = CalibratedClassifierCV(xgb_model, method='isotonic', cv=5)
calibrated_xgb.fit(X_train_scaled, y_train)
# Get the new smoothed probabilities
y_proba_calibrated = calibrated_xgb.predict_proba(X_test_scaled)[:, 1]
# re apply the Youden Index to the CALIBRATED probabilities
fpr_c, tpr_c, threshold_c = roc_curve(y_test, y_proba_calibrated)
youden_c = tpr_c - fpr_c
optimal_idx_c = np.argmax(youden_c)
optimal_threshold_c = threshold_c[optimal_idx_c]
# apply the new optimal threshold
y_pred_calibrated = (y_proba_calibrated >= optimal_threshold_c).astype(int)
# print comparison
print("=" * 50)
print("PROBABILITY SMOOTHING (CALIBRATION)")
print("=" * 50)
print(f"New optimal threshold (calibrated): {optimal_threshold_c:.4f}")
print(f"\nRecall (calibrated): {recall_score(y_test, y_pred_calibrated):.4f}")
print(f"Precision (calibrated): {precision_score(y_test, y_pred_calibrated):.4f}")
print(f"F1-Score (calibrated): {f1_score(y_test, y_pred_calibrated):.4f}")
print(f"Accuracy (calibrated): {accuracy_score(y_test, y_pred_calibrated):.4f}")
print("\nConfusion Matrix (calibrated):")
cm = confusion_matrix(y_test, y_pred_calibrated)
print(cm)
print(f"\n TN: {cm[0,0]} FP: {cm[0,1]}")
print(f" FN: {cm[1,0]} TP: {cm[1,1]}")
# Plot the calibration curve
plt.figure(figsize=(6, 6))
prob_true, prob_pred = calibration_curve(y_test, y_proba_calibrated, n_bins=10)
plt.plot([0, 1], [0, 1], 'k--', label='Perfectly Calibrated')
plt.plot(prob_pred, prob_true, 's-', label='XGBoost (Calibrated)')
plt.xlabel('Predicted Probability')
plt.ylabel('Actual Frequency (True Positive Rate)')
plt.title('Probability Calibration Curve')
plt.legend()
plt.show()
```
#### Insight: Interpreting the Calibration Curve
The calibration curve compares the model's predicted probabilities against
actual outcomes. A perfectly calibrated model would follow the dashed diagonal.
Our calibrated XGBoost model tracks the diagonal reasonably well at low
probabilities (0.1–0.25) but reveals a critical limitation: **at high predicted
probabilities (~0.75), the actual frequency of at-risk students drops to
near zero**.