-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1646 lines (1382 loc) · 64.8 KB
/
main.py
File metadata and controls
1646 lines (1382 loc) · 64.8 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
"""
=============================================================================
DIGITAL CONTENT CONSUMPTION PATTERNS — UNSUPERVISED LEARNING PIPELINE
# =============================================================================
# Stages:
# 1. Exploratory Data Analysis (EDA)
# 2. Data Preprocessing
# 3. Dimensionality Reduction
# 4. Clustering (K-Means & DBSCAN)
# 5. Cluster Profiling & Business Interpretation
# =============================================================================
"""
# =========================================================================
# IMPORTS
# =========================================================================
import os
import warnings
from math import pi
from typing import List, Dict
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from tabulate import tabulate
import sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score, davies_bouldin_score, silhouette_samples
from sklearn.neighbors import NearestNeighbors
import joblib
warnings.filterwarnings('ignore')
# =========================================================================
# GLOBAL CONFIGURATION
# =========================================================================
plt.rcParams.update({
'font.family': 'DejaVu Sans',
'font.size': 10,
'axes.titlesize': 12,
'axes.titleweight': 'bold',
'axes.labelweight': 'bold',
'figure.dpi': 150,
'savefig.dpi': 200,
'savefig.bbox': 'tight',
'savefig.facecolor': 'white'
})
sns.set_theme(style='whitegrid', palette='viridis')
COLORS = {
'primary': '#2C3E50',
'accent': '#E74C3C',
'median': '#27AE60',
'kde': '#3498DB',
'scaled': '#27AE60',
'original': '#3498DB',
'kmeans': '#3498DB',
'dbscan': '#9B59B6',
'silhouette': '#27AE60',
'centroid': '#E74C3C',
'noise': '#7F8C8D',
'grid': '#ECF0F1'
}
RANDOM_STATE = 42
# Project directory structure (created if missing)
TABLES_DIR = "reports/tables"
FIGURES_DIR = "reports/figures"
for _folder in ["data/raw", "data/processed", "notebooks", "src",
"models", "reports/figures", "reports/tables"]:
os.makedirs(_folder, exist_ok=True)
print(f"scikit-learn version: {sklearn.__version__}")
# =========================================================================
# DATA LOADING
# =========================================================================
df = pd.read_csv("data/raw/digital_content_sessions.csv")
numerical_cols = [
'total_time_min', 'pieces_started', 'completion_depth_avg',
'complementary_interactions', 'thematic_diversity',
'pause_count', 'navigation_speed'
]
categorical_cols = ['moment_of_activity', 'device_type', 'used_recommendations']
# =========================================================================
# HELPER FUNCTION
# =========================================================================
def calculate_distribution_stats(data: pd.Series) -> Dict:
"""Calculate comprehensive distribution statistics."""
Q1 = data.quantile(0.25)
Q3 = data.quantile(0.75)
IQR = Q3 - Q1
return {
'mean': data.mean(),
'median': data.median(),
'std': data.std(),
'min': data.min(),
'max': data.max(),
'skewness': data.skew(),
'kurtosis': data.kurtosis(),
'Q1': Q1,
'Q3': Q3,
'IQR': IQR,
'outlier_lower': Q1 - 1.5 * IQR,
'outlier_upper': Q3 + 1.5 * IQR
}
# =========================================================================
# CONSOLE REPORT: STATISTICAL SUMMARY
# =========================================================================
print("\n" + "=" * 100)
print("📊 PHASE 1: EXPLORATORY DATA ANALYSIS — STATISTICAL REPORT")
print("=" * 100)
print(f"Dataset: {df.shape[0]:,} sessions × {df.shape[1]} features\n")
stats_table = []
for col in numerical_cols:
stats_dict = calculate_distribution_stats(df[col].dropna())
stats_table.append([
col.replace('_', ' ').title(),
f"{stats_dict['mean']:.4f}",
f"{stats_dict['median']:.4f}",
f"{stats_dict['std']:.4f}",
f"{stats_dict['min']:.4f}",
f"{stats_dict['max']:.4f}",
f"{stats_dict['skewness']:.4f}",
f"{stats_dict['kurtosis']:.4f}",
f"{stats_dict['Q1']:.4f}",
f"{stats_dict['Q3']:.4f}"
])
headers = [
'Feature', 'Mean', 'Median', 'Std Dev',
'Min', 'Max', 'Skewness', 'Kurtosis', 'Q1', 'Q3'
]
print(tabulate(stats_table, headers=headers, tablefmt='grid',
numalign='center', stralign='left'))
print(f"\n{'=' * 100}\n")
# Save descriptive statistics
pd.DataFrame(stats_table, columns=headers).to_csv(
f"{TABLES_DIR}/descriptive_statistics.csv", index=False)
# =========================================================================
# 1.1 UNIVARIATE DISTRIBUTION ANALYSIS — CLEAN CHARTS
# =========================================================================
fig, axes = plt.subplots(4, 2, figsize=(18, 20))
axes = axes.flatten()
for i, col in enumerate(numerical_cols):
ax = axes[i]
stats_dict = calculate_distribution_stats(df[col].dropna())
# Histogram with KDE
sns.histplot(df[col], kde=True, bins=30, edgecolor='white',
alpha=0.7, linewidth=0.8, color=COLORS['kde'], ax=ax)
# Reference lines for mean and median
ax.axvline(stats_dict['mean'], color=COLORS['accent'], linestyle='--',
linewidth=2, alpha=0.9, label=f"Mean: {stats_dict['mean']:.2f}")
ax.axvline(stats_dict['median'], color=COLORS['median'], linestyle='-',
linewidth=2, alpha=0.9, label=f"Median: {stats_dict['median']:.2f}")
ax.set_title(col.replace('_', ' ').title(),
fontsize=12, pad=15, color=COLORS['primary'])
ax.set_xlabel('')
ax.legend(frameon=True, fancybox=True, fontsize=8, loc='upper right')
if len(numerical_cols) < len(axes):
fig.delaxes(axes[-1])
fig.suptitle('Univariate Distribution Analysis: Numerical Features',
fontsize=16, fontweight='bold', y=1.01, color=COLORS['primary'])
plt.tight_layout()
plt.savefig('reports/figures/univariate_distributions.png',
dpi=200, facecolor='white')
plt.show()
# =========================================================================
# 1.2 BOXPLOT ANALYSIS — VIOLIN-BOX HYBRID
# =========================================================================
fig, axes = plt.subplots(2, 4, figsize=(22, 10))
axes = axes.flatten()
for i, col in enumerate(numerical_cols):
ax = axes[i]
# Violin plot for distribution shape
parts = ax.violinplot(df[col].dropna(), positions=[1],
showmeans=True, showmedians=True)
for pc in parts['bodies']:
pc.set_facecolor('#3498DB')
pc.set_alpha(0.6)
# Boxplot overlay for quartile statistics
ax.boxplot(df[col].dropna(), positions=[1], widths=0.3,
patch_artist=True,
boxprops=dict(facecolor='white', alpha=0.8),
medianprops=dict(color=COLORS['accent'], linewidth=2))
ax.set_title(col.replace('_', ' ').title(),
fontsize=11, pad=12, color=COLORS['primary'])
ax.set_ylabel('')
ax.set_xticks([])
ax.grid(True, alpha=0.3, axis='y')
for j in range(len(numerical_cols), len(axes)):
axes[j].set_visible(False)
fig.suptitle('Distribution & Outlier Visualization: Violin-Box Analysis',
fontsize=15, fontweight='bold', y=1.02)
plt.tight_layout()
plt.savefig('reports/figures/boxplot_outliers.png',
dpi=200, facecolor='white')
plt.show()
# =========================================================================
# 1.3 COMPREHENSIVE OUTLIER ANALYSIS — CONSOLE REPORT
# =========================================================================
print("\n" + "=" * 100)
print("🔍 1.3 COMPREHENSIVE OUTLIER ANALYSIS — IQR METHOD")
print("=" * 100)
outlier_records = []
for col in numerical_cols:
data = df[col].dropna()
stats_dict = calculate_distribution_stats(data)
# Identify outliers
outlier_mask = (data < stats_dict['outlier_lower']) | \
(data > stats_dict['outlier_upper'])
outliers = data[outlier_mask]
# Severity classification
outlier_pct = len(outliers) / len(data)
severity = ('HIGH' if outlier_pct > 0.10 else
'MEDIUM' if outlier_pct > 0.05 else
'LOW')
# Context-aware recommendation
recommendation = (
'Investigate before removal' if severity == 'HIGH'
else 'Flag for context review' if severity == 'MEDIUM'
else 'Likely natural variation'
)
record = {
'Feature': col.replace('_', ' ').title(),
'Q1': f"{stats_dict['Q1']:.4f}",
'Q3': f"{stats_dict['Q3']:.4f}",
'IQR': f"{stats_dict['IQR']:.4f}",
'Lower Bound': f"{stats_dict['outlier_lower']:.4f}",
'Upper Bound': f"{stats_dict['outlier_upper']:.4f}",
'Outlier Count': len(outliers),
'Outlier %': f"{outlier_pct*100:.2f}%",
'Severity': severity,
'Recommendation': recommendation
}
outlier_records.append(record)
# Print per-feature analysis
print(f"\n Feature: {col.replace('_', ' ').title()}")
print(f" Q1: {stats_dict['Q1']:.4f} | Q3: {stats_dict['Q3']:.4f} | "
f"IQR: {stats_dict['IQR']:.4f}")
print(f" Lower Bound: {stats_dict['outlier_lower']:.4f} | "
f"Upper Bound: {stats_dict['outlier_upper']:.4f}")
print(f" Outliers Detected: {len(outliers)} "
f"({outlier_pct*100:.2f}%)")
print(f" Severity: {severity} | Recommendation: {recommendation}")
# Summary table
outlier_df = pd.DataFrame(outlier_records)
print(f"\n{'=' * 100}")
print("OUTLIER ANALYSIS SUMMARY")
print(tabulate(outlier_df[['Feature', 'Outlier Count', 'Outlier %',
'Severity', 'Recommendation']],
headers='keys', tablefmt='grid', showindex=False))
print(f"\n{'=' * 100}\n")
# Save outlier summary
outlier_df.to_csv(f"{TABLES_DIR}/outlier_analysis_summary.csv", index=False)
# =========================================================================
# 1.4 CORRELATION ANALYSIS — PROFESSIONAL HEATMAP
# =========================================================================
corr_matrix = df[numerical_cols].corr(method='spearman')
print("📈 SPEARMAN CORRELATION MATRIX")
print("-" * 100)
corr_display = corr_matrix.copy()
corr_display.index = [c.replace('_', ' ').title() for c in corr_display.index]
corr_display.columns = [c.replace('_', ' ').title() for c in corr_display.columns]
print(tabulate(corr_display, headers='keys', tablefmt='grid',
floatfmt='.4f'))
print(f"\n{'=' * 100}\n")
# Save correlation matrix
corr_matrix.to_csv(f"{TABLES_DIR}/spearman_correlation_matrix.csv")
# Heatmap
fig, ax = plt.subplots(figsize=(14, 10))
mask = np.triu(np.ones_like(corr_matrix, dtype=bool), k=1)
sns.heatmap(
corr_matrix, mask=mask, annot=True, fmt='.2f',
cmap='RdBu_r', center=0, vmin=-1, vmax=1,
square=True, linewidths=1.5, linecolor='white',
cbar_kws={'shrink': 0.8, 'label': 'Spearman ρ'},
annot_kws={'size': 11, 'fontweight': 'bold'},
ax=ax
)
clean_labels = [col.replace('_', ' ').title() for col in numerical_cols]
ax.set_xticklabels(clean_labels, rotation=45, ha='right', fontsize=10)
ax.set_yticklabels(clean_labels, rotation=0, fontsize=10)
ax.set_title('Feature Correlation Structure\nSpearman Rank Correlation Matrix',
fontsize=14, fontweight='bold', pad=25, color=COLORS['primary'])
plt.tight_layout()
plt.savefig('reports/figures/correlation_heatmap.png',
dpi=200, facecolor='white')
plt.show()
# =========================================================================
# 1.5 CATEGORICAL DISTRIBUTION ANALYSIS
# =========================================================================
print("📊 CATEGORICAL FEATURE DISTRIBUTIONS")
print("-" * 100)
categorical_frames = []
for col in categorical_cols:
counts = df[col].value_counts()
pcts = df[col].value_counts(normalize=True) * 100
cat_table = pd.DataFrame({
'Category': counts.index,
'Count': counts.values,
'Percentage': [f"{p:.2f}%" for p in pcts.values]
})
print(f"\n{col.replace('_', ' ').title()}:")
print(tabulate(cat_table, headers='keys', tablefmt='grid', showindex=False))
# Accumulate for export
cat_save = cat_table.copy()
cat_save.insert(0, 'Feature', col)
categorical_frames.append(cat_save)
print(f"\n{'=' * 100}\n")
# Save categorical distributions
pd.concat(categorical_frames, ignore_index=True).to_csv(
f"{TABLES_DIR}/categorical_distributions.csv", index=False)
# Donut charts
fig, axes = plt.subplots(1, 3, figsize=(20, 6))
palettes = ['Blues_r', 'Greens_r', 'Oranges_r']
for i, (col, palette) in enumerate(zip(categorical_cols, palettes)):
value_counts = df[col].value_counts()
wedges, texts, autotexts = axes[i].pie(
value_counts.values,
labels=value_counts.index,
autopct='%1.1f%%',
colors=sns.color_palette(palette, len(value_counts)),
startangle=90,
pctdistance=0.85,
wedgeprops=dict(width=0.4, edgecolor='white', linewidth=2)
)
for autotext in autotexts:
autotext.set_fontsize(9)
autotext.set_fontweight('bold')
autotext.set_color('white')
for text in texts:
text.set_fontsize(10)
text.set_fontweight('600')
axes[i].set_title(col.replace('_', ' ').title(),
fontsize=12, fontweight='bold', pad=20)
plt.suptitle('Categorical Feature Analysis',
fontsize=14, fontweight='bold', y=1.03)
plt.tight_layout()
plt.savefig('reports/figures/categorical_distributions.png',
dpi=200, facecolor='white')
plt.show()
# =========================================================================
# 1.6 PAIRPLOT — MULTIVARIATE RELATIONSHIPS
# =========================================================================
pairplot_features = [
'total_time_min', 'pieces_started', 'completion_depth_avg',
'complementary_interactions', 'thematic_diversity'
]
g = sns.PairGrid(df[pairplot_features], diag_sharey=False)
g.map_upper(sns.scatterplot, alpha=0.4, s=35, edgecolor='none', color='#3498DB')
g.map_lower(sns.regplot, scatter_kws={'alpha': 0.3, 's': 25},
line_kws={'color': '#E74C3C', 'linewidth': 2})
g.map_diag(sns.histplot, kde=True, alpha=0.7, color='#2C3E50')
g.fig.suptitle('Multivariate Relationship Analysis',
fontsize=14, fontweight='bold', y=1.02)
plt.savefig('reports/figures/pairplot_relationships.png',
dpi=200, facecolor='white')
plt.show()
# =========================================================================
# EXECUTIVE SUMMARY
# =========================================================================
print("=" * 100)
print("✅ PHASE 1 COMPLETE — Executive Summary")
print("=" * 100)
print(f" • Total Features Analyzed: {len(numerical_cols)} numerical | "
f"{len(categorical_cols)} categorical")
print(f" • Outlier Summary: See reports/tables/outlier_analysis_summary.csv")
print(f" • Visualizations: 5 charts saved to reports/figures/")
print(f" • Tables: descriptive_statistics, outlier, correlation, categorical -> reports/tables/")
print(f" • Console Reports: Statistical, Outlier, Correlation, Categorical")
print(f" • Ready for Phase 2: Clustering Analysis")
print("=" * 100)
##############################################
"""
=============================================================================
PHASE 2: DATA PREPROCESSING
=============================================================================
Objective: Transform raw session data into a scaled, encoded feature matrix
suitable for distance-based clustering algorithms.
Key Decisions:
- Drop 'navigation_speed': derived feature with extreme kurtosis (358.5)
and redundant with 'pieces_started' + 'total_time_min'
- StandardScaler: zero-mean unit-variance normalization for numerical features
- One-hot encoding: nominal categorical variables without ordinal assumption
- 'used_recommendations': retained as binary indicator (0/1)
- 'pause_count': retained despite zero-inflation; represents valid behavioral signal
=============================================================================
"""
# =========================================================================
# 2.1 DATA LOADING
# =========================================================================
print("\n" + "=" * 100)
print("⚙️ PHASE 2: DATA PREPROCESSING")
print("=" * 100)
df = pd.read_csv("data/raw/digital_content_sessions.csv")
print(f"\nRaw data loaded:{df.shape[0]:,} rows ×{df.shape[1]} columns")
# =========================================================================
# 2.2 FEATURE SELECTION & ENGINEERING DECISIONS
# =========================================================================
print("\n" + "-" * 100)
print("2.2 FEATURE SELECTION DECISIONS")
print("-" * 100)
# Decision 1: Drop navigation_speed
print("\n Decision 1 — Drop 'navigation_speed':")
print(" • Kurtosis: 358.51 (extreme deviation from normality)")
print(" • Minimum value: -1.994 (logically impossible negative speed)")
print(" • Information captured by parent variables: pieces_started + total_time_min")
print(" • Spearman ρ with pieces_started: 0.64")
print(" → Action: Feature excluded from clustering feature matrix")
# Decision 2: Retain pause_count
print("\n Decision 2 — Retain 'pause_count' despite zero-inflation:")
print(" • 14.27% flagged as statistical outliers by IQR method")
print(" • Median = 0, but non-zero values represent meaningful behavioral signal")
print(" • Zero-inflation itself is a clustering signal (sessions with vs. without pauses)")
print(" → Action: Feature retained and scaled")
# Decision 3: Session ID
print("\n Decision 3 — Exclude 'session_id':")
print(" • Unique identifier with no predictive or structural information")
print(" → Action: Stored separately for traceability, excluded from feature matrix")
# =========================================================================
# 2.3 DEFINE FEATURE GROUPS
# =========================================================================
numerical_features = [
'total_time_min',
'pieces_started',
'completion_depth_avg',
'complementary_interactions',
'thematic_diversity',
'pause_count'
# 'navigation_speed' — intentionally excluded
]
categorical_features = ['moment_of_activity', 'device_type']
binary_features = ['used_recommendations']
# Store session IDs for traceability
session_ids = df['session_id'].copy()
# Extract feature matrix components
X_numerical = df[numerical_features].copy()
X_categorical = df[categorical_features].copy()
X_binary = df[binary_features].copy()
print(f"\n Feature matrix composition:")
print(f" Numerical features:{len(numerical_features)} —{numerical_features}")
print(f" Categorical features:{len(categorical_features)} —{categorical_features}")
print(f" Binary features:{len(binary_features)} —{binary_features}")
print(f" Total features before encoding:{len(numerical_features) + len(categorical_features) + len(binary_features)}")
# =========================================================================
# 2.4 DATA QUALITY VERIFICATION
# =========================================================================
print("\n" + "-" * 100)
print("2.4 DATA QUALITY VERIFICATION")
print("-" * 100)
missing_report = pd.DataFrame({
'Feature': numerical_features + categorical_features + binary_features,
'Missing_Values': (list(X_numerical.isnull().sum()) +
list(X_categorical.isnull().sum()) +
list(X_binary.isnull().sum())),
'Data_Type': (list(X_numerical.dtypes.astype(str)) +
list(X_categorical.dtypes.astype(str)) +
list(X_binary.dtypes.astype(str)))
})
missing_report['Status'] = missing_report['Missing_Values'].apply(
lambda x: '✓ Clean' if x == 0 else '⚠ Review Required'
)
print(tabulate(missing_report, headers='keys', tablefmt='grid', showindex=False))
print(f"\n → All features verified complete. No imputation required.")
# Save data quality report
missing_report.to_csv(f"{TABLES_DIR}/data_quality_report.csv", index=False)
# =========================================================================
# 2.5 STANDARDSCALER — NUMERICAL FEATURES
# =========================================================================
print("\n" + "-" * 100)
print("2.5 STANDARDSCALER APPLICATION — NUMERICAL FEATURES")
print("-" * 100)
scaler = StandardScaler()
X_numerical_scaled = scaler.fit_transform(X_numerical)
# Create scaled DataFrame with meaningful column names
X_numerical_scaled_df = pd.DataFrame(
X_numerical_scaled,
columns=[f"{col}_scaled" for col in numerical_features],
index=df.index
)
# Report scaling parameters
scaling_report = pd.DataFrame({
'Feature': numerical_features,
'Mean_Before': X_numerical.mean().round(4).values,
'Std_Before': X_numerical.std().round(4).values,
'Mean_After': X_numerical_scaled_df.mean().round(6).values,
'Std_After': X_numerical_scaled_df.std().round(6).values
})
print("\n Scaling Verification (target: μ≈0, σ≈1 after scaling):")
print(tabulate(scaling_report, headers='keys', tablefmt='grid',
showindex=False, floatfmt='.6f'))
print("\n → StandardScaler applied successfully. All features centered at μ=0, σ=1.")
# Save scaling report
scaling_report.to_csv(f"{TABLES_DIR}/scaling_report.csv", index=False)
# =========================================================================
# 2.6 ONE-HOT ENCODING — CATEGORICAL FEATURES
# =========================================================================
print("\n" + "-" * 100)
print("2.6 ONE-HOT ENCODING — CATEGORICAL FEATURES")
print("-" * 100)
# Apply one-hot encoding — retain all categories for interpretability
X_categorical_encoded = pd.get_dummies(
X_categorical,
columns=categorical_features,
drop_first=False,
dtype=int
)
print(f"\n Categories encoded:")
encoding_records = []
for col in categorical_features:
original_values = df[col].unique()
encoded_cols = [c for c in X_categorical_encoded.columns if c.startswith(col)]
print(f" {col}: {len(original_values)} unique values → {len(encoded_cols)} binary columns")
print(f" Original: {sorted(original_values)}")
print(f" Encoded: {encoded_cols}")
encoding_records.append({
'Feature': col,
'Unique_Values': len(original_values),
'Binary_Columns': len(encoded_cols),
'Original': str(sorted(original_values)),
'Encoded': str(encoded_cols)
})
print(f"\n Categorical features after encoding: {X_categorical_encoded.shape[1]} columns")
# Save one-hot encoding map
pd.DataFrame(encoding_records).to_csv(
f"{TABLES_DIR}/onehot_encoding_map.csv", index=False)
# =========================================================================
# 2.7 FINAL FEATURE MATRIX ASSEMBLY
# =========================================================================
print("\n" + "-" * 100)
print("2.7 FINAL FEATURE MATRIX ASSEMBLY")
print("-" * 100)
# Align all feature groups by index
X_final = pd.concat([
X_numerical_scaled_df,
X_categorical_encoded.reset_index(drop=True),
X_binary.reset_index(drop=True)
], axis=1)
print(f"\n Final feature matrix dimensions: {X_final.shape[0]:,} rows × {X_final.shape[1]} columns")
print(f" Feature list ({X_final.shape[1]} total):")
for i, col in enumerate(X_final.columns, 1):
print(f" {i:2d}. {col}")
# Save final feature matrix column list
pd.DataFrame({'index': range(1, len(X_final.columns) + 1),
'feature': list(X_final.columns)}).to_csv(
f"{TABLES_DIR}/final_feature_matrix_columns.csv", index=False)
# =========================================================================
# 2.8 PREPROCESSING IMPACT VISUALIZATION
# =========================================================================
fig, axes = plt.subplots(2, 3, figsize=(18, 10))
axes = axes.flatten()
for i, col in enumerate(numerical_features):
ax = axes[i]
# Plot original distribution
sns.kdeplot(X_numerical[col], ax=ax, color=COLORS['original'],
label='Original', linewidth=2, alpha=0.7)
# Plot scaled distribution
sns.kdeplot(X_numerical_scaled_df[f"{col}_scaled"], ax=ax,
color=COLORS['scaled'], label='Scaled (μ=0, σ=1)',
linewidth=2, alpha=0.7)
ax.set_title(col.replace('_', ' ').title(), fontsize=11,
fontweight='bold', color=COLORS['primary'])
ax.legend(frameon=True, fontsize=8)
ax.set_xlabel('')
fig.suptitle('Preprocessing Impact: Original vs. Scaled Distributions',
fontsize=14, fontweight='bold', y=1.02, color=COLORS['primary'])
plt.tight_layout()
plt.savefig('reports/figures/preprocessing_scaling_impact.png',
dpi=200, facecolor='white')
plt.show()
# =========================================================================
# 2.9 SAVE PROCESSED DATA
# =========================================================================
print("\n" + "-" * 100)
print("2.9 SAVING PROCESSED DATA")
print("-" * 100)
# Add session_id back for traceability
X_final_with_id = X_final.copy()
X_final_with_id.insert(0, 'session_id', session_ids)
# Save processed feature matrix
output_path = "data/processed/sessions_preprocessed.csv"
X_final_with_id.to_csv(output_path, index=False)
print(f"\n Processed data saved: {output_path}")
# Save scaler parameters for reproducibility
scaler_params = pd.DataFrame({
'feature': numerical_features,
'mean': scaler.mean_,
'std': scaler.scale_
})
scaler_params.to_csv("data/processed/scaler_parameters.csv", index=False)
print(f" Scaler parameters saved: data/processed/scaler_parameters.csv")
#######################
"""
=============================================================================
PHASE 3: DIMENSIONALITY REDUCTION
=============================================================================
Objective: Reduce 14-dimensional feature space via PCA (≥80% variance)
for clustering input; t-SNE for complementary visualization.
Note: scikit-learn ≥1.2 uses 'max_iter' instead of 'n_iter' for TSNE.
=============================================================================
"""
# =========================================================================
# 3.1 LOAD PREPROCESSED DATA
# =========================================================================
print("\n" + "=" * 100)
print("📉 PHASE 3: DIMENSIONALITY REDUCTION")
print("=" * 100)
df_processed = pd.read_csv("data/processed/sessions_preprocessed.csv")
session_ids = df_processed['session_id'].copy()
feature_cols = [col for col in df_processed.columns if col != 'session_id']
X = df_processed[feature_cols].copy()
print(f"\n Input: {X.shape[0]:,} rows × {X.shape[1]} features")
# =========================================================================
# 3.2 PCA — EXPLAINED VARIANCE ANALYSIS
# =========================================================================
print("\n" + "-" * 100)
print("3.2 PRINCIPAL COMPONENT ANALYSIS")
print("-" * 100)
pca_full = PCA(random_state=RANDOM_STATE)
pca_full.fit(X)
explained_variance = pca_full.explained_variance_ratio_
cumulative_variance = np.cumsum(explained_variance)
threshold = 0.80
n_components = np.argmax(cumulative_variance >= threshold) + 1
# Variance report
variance_table = []
for i in range(len(explained_variance)):
variance_table.append([
f"PC{i+1}",
f"{explained_variance[i]:.4f}",
f"{explained_variance[i]*100:.1f}%",
f"{cumulative_variance[i]:.4f}",
f"{cumulative_variance[i]*100:.1f}%"
])
print(f"\n Components retained (≥{threshold*100:.0f}% variance): {n_components}")
print(f" Cumulative variance: {cumulative_variance[n_components-1]*100:.1f}%")
print(f" Dimensionality reduction: {X.shape[1]} → {n_components} features")
print(f"\n Full Variance Breakdown:")
print(tabulate(variance_table,
headers=['Component', 'Variance', '%', 'Cumulative', 'Cumulative %'],
tablefmt='grid', showindex=False))
# Save full variance breakdown
pd.DataFrame(variance_table,
columns=['Component', 'Variance', 'Variance_%',
'Cumulative', 'Cumulative_%']).to_csv(
f"{TABLES_DIR}/pca_variance_breakdown.csv", index=False)
# =========================================================================
# 3.3 EXPLAINED VARIANCE VISUALIZATION
# =========================================================================
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
# Cumulative variance
axes[0].plot(range(1, len(cumulative_variance) + 1), cumulative_variance,
marker='o', color='#3498DB', linewidth=2.5, markersize=8,
markerfacecolor='white', markeredgewidth=2)
axes[0].axhline(y=threshold, color='#E74C3C', linestyle='--', linewidth=2,
label=f'80% Threshold')
axes[0].axvline(x=n_components, color='#27AE60', linestyle=':', linewidth=2,
label=f'{n_components} Components Selected')
axes[0].set_xlabel('Principal Components', fontweight='bold')
axes[0].set_ylabel('Cumulative Explained Variance', fontweight='bold')
axes[0].set_title('Cumulative Explained Variance', fontweight='bold', fontsize=13)
axes[0].legend(frameon=True, fontsize=9)
axes[0].grid(True, alpha=0.3)
axes[0].set_ylim(0, 1.05)
# Scree plot
bars = axes[1].bar(range(1, len(explained_variance) + 1), explained_variance,
color='#3498DB', edgecolor='white', linewidth=1.2)
for i in range(n_components):
bars[i].set_color('#27AE60')
axes[1].set_xlabel('Principal Component', fontweight='bold')
axes[1].set_ylabel('Explained Variance Ratio', fontweight='bold')
axes[1].set_title(f'Scree Plot — {n_components} Components Retained (Green)',
fontweight='bold', fontsize=13)
axes[1].grid(True, alpha=0.3, axis='y')
plt.tight_layout()
plt.savefig('reports/figures/pca_explained_variance.png', dpi=200, facecolor='white')
plt.show()
# =========================================================================
# 3.4 COMPONENT LOADING ANALYSIS
# =========================================================================
print("\n" + "-" * 100)
print("3.4 COMPONENT LOADING ANALYSIS")
print("-" * 100)
loadings = pd.DataFrame(
pca_full.components_[:n_components].T,
columns=[f'PC{i+1}' for i in range(n_components)],
index=feature_cols
)
# Identify dominant features per component
print(f"\n Dominant Features per Component (|loading| > 0.50):")
dominant_records = []
for i in range(n_components):
pc_loadings = loadings[f'PC{i+1}']
strong_features = pc_loadings[pc_loadings.abs() > 0.50].sort_values(ascending=False)
if len(strong_features) > 0:
for feat, val in strong_features.items():
direction = "(+)" if val > 0 else "(-)"
print(f" PC{i+1}: {feat} = {val:.3f} {direction}")
dominant_records.append({'Component': f'PC{i+1}', 'Feature': feat,
'Loading': round(val, 3), 'Direction': direction})
else:
print(f" PC{i+1}: No single feature dominates (distributed loadings)")
dominant_records.append({'Component': f'PC{i+1}', 'Feature': '(distributed)',
'Loading': np.nan, 'Direction': '—'})
# Save dominant features and full loadings matrix
pd.DataFrame(dominant_records).to_csv(
f"{TABLES_DIR}/pca_dominant_features.csv", index=False)
loadings.to_csv(f"{TABLES_DIR}/pca_loadings.csv")
# Loadings heatmap
fig, ax = plt.subplots(figsize=(12, 8))
sns.heatmap(loadings, annot=True, fmt='.2f', cmap='RdBu_r', center=0,
vmin=-1, vmax=1, square=True, linewidths=1.2, linecolor='white',
cbar_kws={'shrink': 0.8, 'label': 'Loading Strength'},
annot_kws={'size': 9, 'fontweight': 'bold'}, ax=ax)
ax.set_title('PCA Component Loadings Matrix\nFeature Contributions to Retained Components',
fontsize=13, fontweight='bold', pad=15)
ax.set_xlabel('Principal Component', fontweight='bold')
ax.set_ylabel('Original Feature', fontweight='bold')
plt.tight_layout()
plt.savefig('reports/figures/pca_loadings_heatmap.png', dpi=200, facecolor='white')
plt.show()
# =========================================================================
# 3.5 APPLY PCA TRANSFORMATION
# =========================================================================
print("\n" + "-" * 100)
print("3.5 APPLYING PCA TRANSFORMATION")
print("-" * 100)
pca = PCA(n_components=n_components, random_state=RANDOM_STATE)
X_pca = pca.fit_transform(X)
df_pca = pd.DataFrame(X_pca, columns=[f'PC{i+1}' for i in range(n_components)])
df_pca.insert(0, 'session_id', session_ids)
print(f"\n PCA transformation: {X.shape[1]} → {n_components} dimensions")
print(f" Variance preserved: {cumulative_variance[n_components-1]*100:.1f}%")
# =========================================================================
# 3.6 t-SNE — NON-LINEAR PROJECTION (COMPATIBLE WITH SCIKIT-LEARN ≥1.2)
# =========================================================================
print("\n" + "-" * 100)
print("3.6 t-SNE — NON-LINEAR PROJECTION")
print("-" * 100)
# scikit-learn ≥1.2 uses 'max_iter' instead of 'n_iter'
tsne = TSNE(
n_components=2,
perplexity=30,
max_iter=1000, # Updated from 'n_iter' for sklearn ≥1.2
random_state=RANDOM_STATE,
init='pca',
learning_rate='auto'
)
X_tsne = tsne.fit_transform(X)
df_tsne = pd.DataFrame(X_tsne, columns=['tSNE_1', 'tSNE_2'])
df_tsne.insert(0, 'session_id', session_ids)
print(f"\n t-SNE projection: {X.shape[1]} → 2 dimensions")
print(f" Perplexity: 30 | Max iterations: 1000")
print(f" KL divergence: {tsne.kl_divergence_:.4f}")
print(f" Note: t-SNE is for visualization only — NOT used as clustering input")
# =========================================================================
# 3.7 DUAL PROJECTION COMPARISON
# =========================================================================
fig, axes = plt.subplots(1, 2, figsize=(16, 7))
# PCA projection
axes[0].scatter(X_pca[:, 0], X_pca[:, 1], c='#3498DB', alpha=0.5, s=35,
edgecolor='white', linewidth=0.3)
axes[0].set_xlabel(f'PC1 ({explained_variance[0]*100:.1f}% variance)', fontweight='bold')
axes[0].set_ylabel(f'PC2 ({explained_variance[1]*100:.1f}% variance)', fontweight='bold')
axes[0].set_title('PCA Projection — Linear Global Structure', fontweight='bold', fontsize=12)
axes[0].grid(True, alpha=0.3)
# t-SNE projection
axes[1].scatter(X_tsne[:, 0], X_tsne[:, 1], c='#E67E22', alpha=0.5, s=35,
edgecolor='white', linewidth=0.3)
axes[1].set_xlabel('t-SNE Dimension 1', fontweight='bold')
axes[1].set_ylabel('t-SNE Dimension 2', fontweight='bold')
axes[1].set_title('t-SNE Projection — Non-Linear Local Structure', fontweight='bold', fontsize=12)
axes[1].grid(True, alpha=0.3)
fig.suptitle('Dimensionality Reduction: Dual Perspective\n'
'PCA (Clustering Input) vs. t-SNE (Visual Validation)',
fontsize=14, fontweight='bold', y=1.02)
plt.tight_layout()
plt.savefig('reports/figures/dual_projection_comparison.png', dpi=200, facecolor='white')
plt.show()
# =========================================================================
# 3.8 SAVE ALL RESULTS
# =========================================================================
print("\n" + "-" * 100)
print("3.8 SAVING RESULTS")
print("-" * 100)
df_pca.to_csv("data/processed/sessions_pca.csv", index=False)
df_tsne.to_csv("data/processed/sessions_tsne.csv", index=False)
loadings.to_csv("data/processed/pca_loadings.csv")
# Save PCA parameters
pca_params = pd.DataFrame({
'component': [f'PC{i+1}' for i in range(n_components)],
'explained_variance': pca.explained_variance_ratio_,
'cumulative_variance': np.cumsum(pca.explained_variance_ratio_)
})
pca_params.to_csv("data/processed/pca_parameters.csv", index=False)
print(f" ✓ sessions_pca.csv — PCA-transformed data ({n_components} dimensions)")
print(f" ✓ sessions_tsne.csv — t-SNE projection (2 dimensions)")
print(f" ✓ pca_loadings.csv — Component loadings matrix")
print(f" ✓ pca_parameters.csv — Explained variance per component")
# =========================================================================
# 3.9 PHASE 3 COMPLETION
# =========================================================================
print("\n" + "=" * 100)
print("✅ PHASE 3: DIMENSIONALITY REDUCTION — COMPLETE")
print("=" * 100)
summary = {
"Input Features": X.shape[1],
"PCA Components Retained": n_components,
"Variance Preserved": f"{cumulative_variance[n_components-1]*100:.1f}%",
"Reduction": f"{X.shape[1]} → {n_components}",
"t-SNE Dimensions": 2,
"t-SNE KL Divergence": f"{tsne.kl_divergence_:.4f}",
}
for k, v in summary.items():
print(f" {k}: {v}")
print("\n Next: Phase 4 — Clustering (K-Means & DBSCAN)")
print("=" * 100)
"""
=============================================================================
PHASE 4: UNSUPERVISED CLUSTERING — K-MEANS & DBSCAN
=============================================================================
Objective: Discover natural behavioral segments using two complementary
algorithms. Diagnose algorithm suitability and select best model.
Data: 1,500 sessions × 3 PCA components (80.7% variance preserved)
=============================================================================
"""
# =========================================================================
# DATA LOADING
# =========================================================================
print("\n" + "═" * 80)
print("📊 PHASE 4: UNSUPERVISED CLUSTERING")
print("═" * 80)
df_pca = pd.read_csv("data/processed/sessions_pca.csv")
session_ids = df_pca['session_id'].copy()
X_pca = df_pca[['PC1', 'PC2', 'PC3']].values
print(f"\n Clustering Input")
print(f" {'─' * 40}")
print(f" Sessions : {X_pca.shape[0]:,}")
print(f" Features : {X_pca.shape[1]} PCA components")
print(f" Variance : 80.7% preserved")