-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotebook.py
More file actions
2611 lines (2228 loc) · 92.7 KB
/
Copy pathnotebook.py
File metadata and controls
2611 lines (2228 loc) · 92.7 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
import marimo
__generated_with = "0.23.14"
app = marimo.App()
@app.cell
def _():
import marimo as mo
return (mo,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# Group 27 — Course-Drop Prediction (Nova Academy)
**Submitters:** Ron Drach · Rotem David Semah
---
This notebook follows the project from understanding the data through preparation, modelling, evaluation, and interpretation.
""")
return
@app.cell
def _():
from functools import wraps
from inspect import getsource
import warnings
from pathlib import Path
from textwrap import dedent
from joblib import dump, hash as joblib_hash, load
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib_inline.backend_inline import set_matplotlib_formats
import seaborn as sns
import shap
from catboost import CatBoostClassifier
from lightgbm import LGBMClassifier
from scipy.stats import rankdata
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score, classification_report, RocCurveDisplay, PrecisionRecallDisplay, ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from xgboost import XGBClassifier
from IPython.display import display
def cache(fn):
cache_dir = Path('.cache/joblib') / fn.__name__
source_hash = joblib_hash(dedent(getsource(fn)))
@wraps(fn)
def wrapped(*args, **kwargs):
path = cache_dir / f'{joblib_hash((source_hash, args, kwargs))}.joblib'
if path.exists():
return load(path)
result = fn(*args, **kwargs)
path.parent.mkdir(parents=True, exist_ok=True)
dump(result, path)
return result
return wrapped
sns.set_theme(style='whitegrid', palette='colorblind', rc={'figure.constrained_layout.use': False})
set_matplotlib_formats('png')
pd.set_option('display.max_columns', None)
TRAIN_PATH = 'data/Train_Data.csv'
TEST_PATH = 'data/Test_Data_No_Target.csv'
TARGET = 'Dropped_Course'
SEED = 42
def load_raw(path: str) -> pd.DataFrame:
return pd.read_csv(path, parse_dates=['Course_Start_Date'])
def show(fig=None):
if fig is None:
fig = plt.gcf()
display(fig)
plt.close(fig)
def subplot_grid(nrows=1, ncols=1, **kwargs):
kwargs.setdefault('layout', 'constrained')
kwargs.setdefault('figsize', (10, 4.375 * nrows))
return plt.subplots(nrows, ncols, **kwargs)
return (
CatBoostClassifier,
ConfusionMatrixDisplay,
LGBMClassifier,
LogisticRegression,
MLPClassifier,
OneHotEncoder,
PrecisionRecallDisplay,
RocCurveDisplay,
SEED,
StandardScaler,
TARGET,
TEST_PATH,
TRAIN_PATH,
XGBClassifier,
average_precision_score,
cache,
classification_report,
display,
load_raw,
np,
pd,
plt,
rankdata,
roc_auc_score,
shap,
show,
sns,
subplot_grid,
train_test_split,
)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# 1. Business understanding
Nova Academy prepares cloud environments, catering, equipment, and classroom capacity before each B2B course begins. A cancellation therefore wastes prepared resources and can leave capacity that could have been offered to another group.
Our goal is to estimate cancellation risk for new registrations early enough to support operational decisions. The assignment requires a continuous `Drop_Probability` output and evaluates its ranking quality with ROC-AUC; the minimum required AUC is 0.70.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# 2. Data loading & first look
Two files are provided:
- `Train_Data.csv` — historical registrations **with** the `Dropped_Course`
label.
- `Test_Data_No_Target.csv` — registrations to score, **without** the label.
Each row is one registration, identified by `Client_ID`. We first inspect inferred types, missingness, cardinality, common values, and zeros before deciding how any column should be treated.
""")
return
@app.cell
def _(TEST_PATH, TRAIN_PATH, display, load_raw, pd):
train_raw = load_raw(TRAIN_PATH)
test_raw = load_raw(TEST_PATH)
print(f"train: {train_raw.shape[0]:,} rows x {train_raw.shape[1]} cols")
print(f"test : {test_raw.shape[0]:,} rows x {test_raw.shape[1]} cols")
data_dictionary = pd.DataFrame({
"dtype": train_raw.dtypes.astype(str),
"n_missing": train_raw.isna().sum(),
"missing_%": (train_raw.isna().mean() * 100).round(2),
"n_unique": train_raw.nunique(dropna=True),
"n_zero": (train_raw == 0).sum(numeric_only=False),
"most_frequent": train_raw.mode(dropna=True).iloc[0],
})
display(data_dictionary)
return test_raw, train_raw
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
**What the dictionary tells us.**
- `Client_ID` is unique per row
- `Agent_ID` and `Company_ID` were inferred as numeric even though they are identifiers, so we convert them to strings after this first inspection. `Company_ID` is also missing for most rows.
- Several text fields have unexpectedly high cardinality. We inspect their raw values later before deciding whether that reflects real variety or inconsistent spelling.
- The numeric summary below lets us look for suspicious ranges and extreme values.
""")
return
@app.cell
def _(test_raw, train_raw):
for id_frame in (train_raw, test_raw):
for id_col in ("Agent_ID", "Company_ID"):
id_frame[id_col] = id_frame[id_col].astype("string")
train_raw.describe()
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 2.1 Target balance
We first check whether one target class is rare enough to require special treatment during training or evaluation.
""")
return
@app.cell
def _(TARGET, display, pd, show, subplot_grid, train_raw):
target_counts = train_raw[TARGET].value_counts().sort_index()
target_rate = train_raw[TARGET].value_counts(normalize=True).sort_index()
balance = pd.DataFrame({
'count': target_counts,
'rate_%': (target_rate * 100).round(1),
})
balance.index = ['0 = completed', '1 = dropped']
display(balance)
balance_fig, balance_ax = subplot_grid()
balance['rate_%'].plot.bar(ax=balance_ax)
balance_ax.set(
title='Course outcomes in the training data', xlabel='', ylabel='share (%)'
)
balance_ax.tick_params(axis='x', rotation=0)
show(balance_fig)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
The target is moderately balanced: 58.6% completed and 41.4% dropped.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# 3. Exploratory Data Analysis
We begin with the target and date coverage, then inspect missingness, categorical quality, and numeric relationships.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 3.1 Train and test dates
We plot the monthly drop rate across the _training_ period and overlay where training ends and where the hidden test window ends.
""")
return
@app.cell
def _(TARGET, show, subplot_grid, test_raw, train_raw):
train_end = train_raw['Course_Start_Date'].max()
test_start = test_raw['Course_Start_Date'].min()
test_end = test_raw['Course_Start_Date'].max()
print(
f"train dates: {train_raw['Course_Start_Date'].min().date()} -> {train_end.date()}"
)
print(f'test dates: {test_start.date()} -> {test_end.date()}')
monthly = (
train_raw.set_index('Course_Start_Date').resample('MS')[TARGET].mean().mul(100)
)
monthly_fig, monthly_ax = subplot_grid()
monthly.plot(marker='o', ax=monthly_ax)
monthly_ax.axhline(
train_raw[TARGET].mean() * 100, linestyle='--', label='train average'
)
monthly_ax.axvline(
train_end, linestyle='--', label=f'train ends ({train_end.date()})'
)
monthly_ax.axvline(test_end, linestyle=':', label=f'test ends ({test_end.date()})')
monthly_ax.set(
xlim=(train_raw['Course_Start_Date'].min(), test_end),
ylabel='drop rate (%)',
title='Drop rate over time — training period and the hidden test horizon',
)
monthly_ax.legend()
show(monthly_fig)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Training covers July 2015 through April 2017. The test set begins at the end of that period and continues through August 2017, so the prediction task is temporal: learn from earlier registrations and score a later window.
The monthly drop rate also changes across the training period. Because a random split would mix earlier and later regimes, we define validation chronologically and later compare the result with a random split.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 3.2 Missing values
We compare missingness in train and test, then ask whether _the fact of being missing_ is itself predictive.
""")
return
@app.cell
def _(display, pd, test_raw, train_raw):
missing_compare = pd.DataFrame({
"train_missing_%": train_raw.isna().mean().mul(100).round(2),
"test_missing_%": test_raw.isna().mean().mul(100).round(2),
})
missing_compare = missing_compare[
(missing_compare["train_missing_%"] > 0)
| (missing_compare["test_missing_%"] > 0)
].sort_values("train_missing_%", ascending=False)
display(missing_compare)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Most train/test missingness rates are close. We next check whether the presence of a value is associated with the target.
""")
return
@app.cell
def _(TARGET, display, pd, train_raw):
missingness_cols = [
'Company_ID',
'Agent_ID',
'Registration_Days_Before',
'Physical_Course_Kits',
'Daily_Tuition_Cost',
'Payment_Terms',
]
missing_summary = (
pd
.concat(
{
col: train_raw
.assign(is_missing=train_raw[col].isna())
.groupby('is_missing')[TARGET]
.agg(count='size', drop_rate='mean')
for col in missingness_cols
},
names=['column'],
)
.reset_index()
.assign(drop_rate_pct=lambda df: (df['drop_rate'] * 100).round(1))
.drop(columns='drop_rate')
.rename(columns={'drop_rate_pct': 'drop_rate_%'})
)
display(missing_summary)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Rows without a `Company_ID` have a noticeably higher drop rate, and `Agent_ID` presence also separates groups. This motivates explicit presence flags instead of replacing missing identifiers with a typical value.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 3.3 Inspecting categorical values
Several text columns have far more distinct values than their meanings suggest: hundreds of payment terms, colors, and enrollment types would be surprising. We inspect the raw labels before deciding whether the cardinality is real.
""")
return
@app.cell
def _(train_raw):
TEXT_COLS = list(train_raw.select_dtypes(include=['object']).columns)
N_COUNT = 9
for text_col in TEXT_COLS:
top_values = train_raw[text_col].value_counts(normalize=True).head(N_COUNT)
cats = [
f'{value!r}: ({share * 100:.1f}%)' for value, share in top_values.items()
]
cats_str = '\n'.join(
' | '.join(cats[i : i + 3]) for i in range(0, len(cats), 3)
)
print(
f"\n{'=' * 80}\n{text_col} ({train_raw[text_col].nunique()} unique values)\n\n{cats_str}\n"
)
return (TEXT_COLS,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
The raw values explain much of the inflated cardinality. Labels such as `'BLUE'`, `'blue'`, and `' Blue '` describe the same category but are stored separately; punctuation and placeholder strings create similar splits in other fields. Before treating these columns as genuinely high-cardinality, we normalize the obvious formatting variants and measure how many levels remain.
""")
return
@app.cell
def _(pd):
# Placeholder strings that mean "missing", in any casing/padding after canonicalisation.
COMMON_NANS = {
'',
'-',
'--',
'.',
'?',
'na',
'n/a',
'nan',
'none',
'null',
'unknown',
'unknonwn',
}
COUNTRY_ALIASES = {'cn': 'chn'} # both mean China
def canonicalize(s: pd.Series) -> pd.Series:
s = s.astype('string').str.strip().str.lower()
return (
s.str
.replace('\\band\\b', '&', regex=True)
.str.replace('[^a-z0-9&() .+-]+', '', regex=True)
.str.replace('\\s+', ' ', regex=True)
.str.strip()
)
return COMMON_NANS, COUNTRY_ALIASES, canonicalize
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
We normalize case, surrounding whitespace, repeated spaces, and injected punctuation. Placeholder labels such as `Unknown` and `?` become missing values rather than new categories. The same deterministic cleaning function will be applied to train and test.
""")
return
@app.cell
def _(COMMON_NANS, COUNTRY_ALIASES, TEXT_COLS, canonicalize, pd):
CAT_COLS = TEXT_COLS + ['Agent_ID', 'Company_ID']
def normalize_cats(df: pd.DataFrame) -> pd.DataFrame:
"""Canonicalise every categorical, then map junk placeholders to NaN."""
df = df.copy()
for col in CAT_COLS:
s = canonicalize(df[col])
df[col] = s.mask(s.isin(COMMON_NANS))
df['Origin_Country'] = df['Origin_Country'].replace(COUNTRY_ALIASES)
return df
return (normalize_cats,)
@app.cell
def _(TEXT_COLS, display, normalize_cats, pd, train_raw):
clean_train = normalize_cats(train_raw)
cardinality_change = (
pd
.DataFrame({
"raw_unique": {c: train_raw[c].nunique() for c in TEXT_COLS},
"clean_unique": {c: clean_train[c].nunique() for c in TEXT_COLS},
})
.assign(collapsed=lambda t: t["raw_unique"] - t["clean_unique"])
.sort_values("collapsed", ascending=False)
)
display(cardinality_change)
return (clean_train,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
The before/after table confirms that most of the apparent variety was formatting noise: `Payment_Terms` falls from 236 raw labels to 3 cleaned levels, and `Client_Category` from 505 to 7. Columns that were already consistent remain unchanged.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 3.4 Which categories actually relate to dropping?
We start with business fields that have only a few cleaned levels, where a direct plot remains readable. Country and identifiers need separate treatment because hundreds of levels would make the same plot misleading.
""")
return
@app.cell
def _(TARGET, TEXT_COLS, clean_train, show, subplot_grid):
def plot_dropout_by_category(df, col, ax, min_count=50, top_n=10):
stats = df.groupby(col, dropna=False)[TARGET].agg(
drop_rate="mean", count="size"
)
stats = (
stats[stats["count"] >= min_count]
.sort_values("count", ascending=False)
.head(top_n)
.sort_values("drop_rate")
)
labels = [f"{i}\n(n={int(r['count'])})" for i, r in stats.iterrows()]
overall = df[TARGET].mean()
ax.barh(
labels,
stats["drop_rate"] * 100,
color=["C1" if rate > overall else "C0" for rate in stats["drop_rate"]],
)
ax.axvline(overall * 100, linestyle="--")
ax.set(
xlabel="Drop rate (%)",
title=f"Drop rate by\n{col.replace('_', ' ')}",
)
category_features = [col for col in TEXT_COLS if col != "Origin_Country"]
category_rows = (len(category_features) + 1) // 2
category_fig, category_axes = subplot_grid(
category_rows, 2, figsize=(10, 3.4 * category_rows)
)
for category_ax, category_feature in zip(category_axes.flat, category_features):
plot_dropout_by_category(clean_train, category_feature, category_ax)
for unused_category_ax in category_axes.flat[len(category_features) :]:
unused_category_ax.set_visible(False)
show(category_fig)
return (plot_dropout_by_category,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
`Payment_Terms` shows the strongest category-level separation: almost all prepaid, non-refundable registrations dropped, compared with roughly 30% of pay-on-start registrations. Because the field's recording time is unknown, we retain it provisionally and treat it as a possible timing-leakage risk.
`Welcome_Gift_Type` and `Lanyard_Color` show little relationship with dropping. The `Assigned_Lab_Config` pattern may partly reflect the standard PC being the default.
The other plots also show useful separation. Direct-website and dedicated-sales registrations drop less often than reseller traffic, organisational enrollment is lower-risk than general admission, and client segments differ. These fields are therefore retained as descriptive predictors rather than causal explanations.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
### A closer look at high-cardinality categories
`Origin_Country`, `Agent_ID`, and `Company_ID` have too many levels for an unfiltered chart. We examine country first, keeping only sufficiently large groups; Portugal is a compact example because it is both the largest country group and far from the overall drop rate. We then inspect agent and company information separately.
""")
return
@app.cell
def _(TARGET, clean_train, display, pd, show, sns, subplot_grid):
country_min_n = 150
country_top_n = 12
overall_drop = clean_train[TARGET].mean()
country_stats = (
clean_train
.groupby('Origin_Country', dropna=False)[TARGET]
.agg(count='size', drop_rate='mean')
.assign(
drop_rate_pct=lambda d: d['drop_rate'] * 100,
lift_pp=lambda d: (d['drop_rate'] - overall_drop) * 100,
)
)
top_by_size = country_stats.sort_values('count', ascending=False).head(
country_top_n
)
extreme_by_lift = (
country_stats[country_stats['count'] >= country_min_n]
.iloc[
lambda d: (
d['lift_pp']
.abs()
.sort_values(ascending=False)
.index.map(d.index.get_loc)
)
]
.head(country_top_n)
)
def plot_country_dropout(stats, title, ax):
stats = stats.sort_values('drop_rate_pct')
labels = [
f"{(idx if pd.notna(idx) else '<missing>')} (n={int(row['count']):,})"
for idx, row in stats.iterrows()
]
below, above = sns.color_palette(n_colors=2)
colors = [above if lift >= 0 else below for lift in stats['lift_pp']]
ax.barh(labels, stats['drop_rate_pct'], color=colors)
ax.axvline(
overall_drop * 100,
linestyle='--',
label=f'overall ({overall_drop * 100:.1f}%)',
)
ax.set(xlabel='drop rate (%)', title=title)
ax.legend()
plots = [
(top_by_size, f'Drop rate by largest {country_top_n} countries'),
(extreme_by_lift, f'Most unusual country drop rates (n >= {country_min_n})'),
]
country_fig, country_axes = subplot_grid(1, 2)
for country_ax, (country_plot_stats, country_title) in zip(country_axes, plots):
plot_country_dropout(country_plot_stats, country_title, country_ax)
show(country_fig)
display(
country_stats
.sort_values('count', ascending=False)
.head(country_top_n)[['count', 'drop_rate_pct', 'lift_pp']]
.round(2)
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Portugal contains 26,429 registrations and has a 63.8% drop rate, making it both the largest country group and the clearest geographic difference. We use it to investigate whether country overlaps with agents, channels, or other parts of the acquisition process.
""")
return
@app.cell
def _(TARGET, clean_train, display, np):
is_portugal = (
clean_train["Origin_Country"].eq("prt").fillna(False).to_numpy(dtype=bool)
)
country_group = np.where(is_portugal, "Portugal", "Other countries")
portugal_summary = (
clean_train
.assign(country_group=country_group)
.groupby("country_group")[TARGET]
.agg(count="size", drop_rate="mean")
.assign(drop_rate_pct=lambda d: d["drop_rate"] * 100)
)
display(portugal_summary[["count", "drop_rate_pct"]].round(1))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Compared with all other countries, Portugal remains clearly different. We next inspect the identifier fields as categories, not numbers, to see whether they show related structure.
""")
return
@app.cell
def _(
TARGET,
clean_train,
display,
plot_dropout_by_category,
show,
subplot_grid,
train_raw,
):
company_presence = train_raw.groupby(train_raw['Company_ID'].notna())[TARGET].agg(
count='size', drop_rate='mean'
)
company_presence.index = ['no company_id', 'has company_id']
identifier_fig, identifier_axes = subplot_grid(1, 2)
plot_dropout_by_category(
clean_train, 'Agent_ID', identifier_axes[0], min_count=150, top_n=12
)
identifier_axes[1].bar(company_presence.index, company_presence['drop_rate'] * 100)
identifier_axes[1].set(
ylabel='drop rate (%)', title='Drop rate by Company_ID presence'
)
show(identifier_fig)
display(company_presence)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Frequent agents have different drop rates, while registrations with a `Company_ID` drop less often (21.2% versus 42.5%). These relationships may overlap with geography, so we perform a small check: does knowing the agent improve country prediction over always guessing the most common country?
""")
return
@app.cell
def _(SEED, clean_train, display, pd, train_test_split):
agent_country_pairs = clean_train[["Agent_ID", "Origin_Country"]].dropna()
country_tr, country_va = train_test_split(
agent_country_pairs, test_size=0.25, random_state=SEED
)
majority_country = country_tr["Origin_Country"].mode().iat[0]
agent_country_map = country_tr.groupby("Agent_ID")["Origin_Country"].agg(
lambda s: s.value_counts().idxmax()
)
agent_country_pred = (
country_va["Agent_ID"].map(agent_country_map).fillna(majority_country)
)
display(
pd.DataFrame({
"check": ["majority country baseline", "agent modal country"],
"accuracy": [
country_va["Origin_Country"].eq(majority_country).mean(),
agent_country_pred.eq(country_va["Origin_Country"]).mean(),
],
}).round(3)
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Agent-based prediction raises country accuracy from 0.391 to 0.421, indicating modest overlap between the two fields. Both are included using the compact representation introduced during preparation.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 3.5 Numeric features: summary, correlation, and suspects
We now inspect numeric ranges, distributions, and their linear correlations with the target.
""")
return
@app.cell
def _(TARGET, display, train_raw):
ID_LIKE = ["Client_ID", "Agent_ID", "Company_ID"]
num_cols = [
c
for c in train_raw.select_dtypes(include=["int64", "float64"]).columns
if c not in ID_LIKE + [TARGET]
]
numeric_summary = (
train_raw[num_cols].agg(['mean', 'median', 'std', 'min', 'max', 'skew']).T
)
numeric_summary.insert(0, 'missing_%', train_raw[num_cols].isna().mean() * 100)
numeric_summary.insert(
1, 'corr_target', train_raw[num_cols].corrwith(train_raw[TARGET])
)
numeric_summary = (
numeric_summary
.round({
'missing_%': 1,
'corr_target': 3,
'mean': 2,
'median': 2,
'std': 2,
'min': 2,
'max': 2,
'skew': 2,
})
.rename_axis('column')
.reset_index()
.sort_values('corr_target', key=abs, ascending=False)
)
display(numeric_summary)
return (num_cols,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
The maximum values reveal several likely data errors: `Students_Count` reaches 9999, and `Practical_Hours` contains both negative values and values up to 10000. We leave the raw values unchanged for this first inspection and decide how to handle them in the outlier section.
""")
return
@app.cell
def _(TARGET, num_cols, plt, show, sns, train_raw):
corr = train_raw[num_cols + [TARGET]].corr()
corr_fig, corr_ax = plt.subplots(figsize=(12, 7), layout='constrained')
sns.heatmap(corr, annot=True, fmt='.2f', cmap='coolwarm', center=0, ax=corr_ax)
corr_ax.set_title('Numeric correlation heatmap (incl. target)')
corr_ax.grid(False)
show(corr_fig)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
No raw numeric feature has an extremely strong Pearson correlation with the target. `Registration_Days_Before` and `Pre_Course_Supports_Tickets` stand out most, while inter-feature correlations are generally modest. Because Pearson correlation measures linear association and is sensitive to extremes, we next use binned drop rates to inspect the shape of the strongest relationships.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 3.6 Numeric drop-rate profiles
Binning a couple of the more predictive numeric features shows _how_ risk moves with them (not just whether they correlate linearly).
""")
return
@app.cell
def _(TARGET, pd, show, subplot_grid, train_raw):
def plot_dropout_by_bins(df, col, bins, ax):
tmp = df[[col, TARGET]].dropna().copy()
tmp['bin'] = pd.qcut(tmp[col], q=bins, duplicates='drop')
stats = tmp.groupby('bin', observed=True)[TARGET].mean().mul(100)
stats.plot.bar(ax=ax)
ax.axhline(df[TARGET].mean() * 100, linestyle='--', label='mean')
ax.set(ylabel='drop rate (%)', title=f'Drop rate by {col} bins')
ax.legend()
ax.tick_params(axis='x', labelrotation=45)
numeric_bin_specs = [
('Registration_Days_Before', 8),
('Pre_Course_Supports_Tickets', 6),
]
numeric_bin_fig, numeric_bin_axes = subplot_grid(1, 2)
for numeric_bin_ax, (numeric_feature, bins) in zip(
numeric_bin_axes, numeric_bin_specs
):
plot_dropout_by_bins(train_raw, numeric_feature, bins, numeric_bin_ax)
show(numeric_bin_fig)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Drop rate rises across longer registration lead times, which suggests that plans are more likely to change when courses are booked far in advance. More pre-course support tickets are associated with lower dropping, suggesting that early engagement may reflect stronger commitment.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 3.7 EDA conclusions
Several observations now guide preparation and modelling:
- Missing `Company_ID`, support activity, registration channel, enrollment type, and lead time all separate groups with different drop rates. Together, these patterns suggest a broader difference in buyer commitment.
- `Payment_Terms` is unusually strong and counter-intuitive. We retain it provisionally, while treating its recording time as an unresolved limitation.
- Country and agent both contain signal and overlap slightly. Their many levels require a compact encoding instead of a large one-hot expansion.
- The later test window and changing monthly rates make time-aware validation important. We therefore use a future holdout and represent both seasonality and longer-term time.
- Some numeric values are clearly suspicious, while other large values may be legitimate rare cases. We will correct only the values for which we have evidence of an error.
These conclusions support comparing a flexible nonlinear model with linear and neural baselines on the same future holdout.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# 4. Missing-value handling & outlier analysis
We now turn the EDA findings into reproducible preparation rules. The same fitted rules must be applied to later data, but the exact missing-value treatment can differ by model family.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## 4.1 Inspecting and handling outliers
We look for values that are physically impossible or absurdly far from the bulk.
""")
return
@app.cell
def _(display, num_cols, pd, test_raw, train_raw):
def sus_report(df, cols, max_mult=10):
out = []
for c in cols:
s = df[c].dropna()
q99 = s.quantile(0.99)
iqr = s.quantile(0.75) - s.quantile(0.25)
scale = max(q99, iqr, 1.0)
why = []
if s.min() < 0:
why.append("negative values")
if s.max() > max_mult * scale:
why.append(f"max={s.max():g} >> q99={q99:g}")
if why:
out.append({
"column": c,
"min": s.min(),
"max": s.max(),
"q99": round(q99, 1),
"why": "; ".join(why),
})
return pd.DataFrame(out)
print("Suspect columns — TRAIN")
display(sus_report(train_raw, num_cols))
print("Suspect columns — TEST")
display(sus_report(test_raw, num_cols))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
The test set introduces no new forms of corruption, suggesting the same cleaning policy can be safely shared. Comparing the maximum values to the 99th percentile helps identify columns with extreme outliers:
""")
return
@app.cell
def _(pd, show, sns, test_raw, train_raw):
TAIL_CHECK_COLS = [
"Students_Count",
"Practical_Hours",
"Daily_Tuition_Cost",
"Prev_Course_Attended",
"Waiting_List_Days",
"Registration_Changes",
]
tail_long = pd.concat(
[
df[col].dropna().rename('value').to_frame().assign(split=split, column=col)
for split, df in [('train', train_raw), ('test', test_raw)]
for col in TAIL_CHECK_COLS
],
ignore_index=True,
)
grid = sns.catplot(
data=tail_long,
x='split',
y='value',
hue='split',
col='column',
col_wrap=3,
kind='box',
sharey=False,
height=3.2,
aspect=1.05,
palette='colorblind',
legend=False,
flierprops={'markersize': 3, 'alpha': 0.35},
)
grid.set_axis_labels('', 'Raw value (log-like scale)').set_titles('{col_name}')
for tail_column, tail_ax in grid.axes_dict.items():
tail_values = tail_long.loc[tail_long['column'].eq(tail_column), 'value']
tail_ax.set_yscale('symlog' if tail_values.min() < 0 else 'log')
tail_ax.set_title(tail_column.replace('_', ' '))
grid.figure.suptitle('Train/test tail comparison', fontsize=15)
grid.figure.set_layout_engine('constrained')
show(grid.figure)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
The box plots identify three clear data-entry errors, so we apply:
- `Students_Count <= 10`: the values beyond the observed low-count support are repeated `9999` placeholders in both train and test. The cap keeps those rows as large groups without treating 9999 as a real count.
- `Practical_Hours` in `[0, 12]`: negative values are impossible, and `5000`/`10000` are clear placeholders. A 12-hour upper bound still allows a long practical day and prevents corrupted placeholder values from distorting the feature space.
- `Daily_Tuition_Cost <= 600`: train has a single `5400` value, while the test maximum is 510. A cap of 600 leaves the observed test range untouched and prevents one corrupted training value from dominating cost calculations.
Other flagged count columns (`Prev_Course_Dropouts`, `Prev_Course_Attended`, `Registration_Changes`, and test-side `Waiting_List_Days`) have long but plausible tails (as seen in the box-plots), so we leave them unchanged and restrict clipping to the three apparent data-entry errors above.
""")
return
@app.cell
def _(display, pd, show, subplot_grid, test_raw, train_raw):
CAP_RULES = {
'Students_Count': (None, 10),
'Practical_Hours': (0, 12),
'Daily_Tuition_Cost': (None, 600),
}
cap_rows = []
for cap_col, (lower, upper) in CAP_RULES.items():
train_capped = train_raw[cap_col].clip(lower=lower, upper=upper)
test_capped = test_raw[cap_col].clip(lower=lower, upper=upper)
cap_rows.append({
'column': cap_col,
'train_rows_affected': int(
(train_raw[cap_col].notna() & train_capped.ne(train_raw[cap_col])).sum()
),
'test_rows_affected': int(
(test_raw[cap_col].notna() & test_capped.ne(test_raw[cap_col])).sum()
),
})
display(pd.DataFrame(cap_rows))