-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1512 lines (1257 loc) Β· 61.3 KB
/
main.py
File metadata and controls
1512 lines (1257 loc) Β· 61.3 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 streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler, LabelEncoder
from sklearn.impute import SimpleImputer, KNNImputer
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.feature_selection import VarianceThreshold
from scipy import stats
from datetime import datetime
import tempfile
import os
import warnings
import plotly.express as px
import plotly.graph_objects as go
warnings.filterwarnings('ignore')
# Fixed CSS styling for better text visibility
def add_custom_css():
st.markdown("""
<style>
/* Import modern font */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
/* Global background and text styling */
.stApp {
background-color: #000000 !important;
}
html, body, [class*="css"] {
font-family: 'Inter', sans-serif !important;
background-color: #000000 !important;
color: #ffffff !important;
}
/* Main container styling */
.main .block-container {
padding-top: 2rem !important;
padding-bottom: 2rem !important;
max-width: 1200px !important;
background-color: #000000 !important;
}
/* Text elements - white text on black background */
.stMarkdown p, .stMarkdown li, .stMarkdown span {
color: #ffffff !important;
font-weight: 400 !important;
line-height: 1.6 !important;
}
.stMarkdown h1, .stMarkdown h2, .stMarkdown h3, .stMarkdown h4 {
color: #ffffff !important;
font-weight: 600 !important;
margin-bottom: 1rem !important;
}
/* Form elements styling */
.stSelectbox label, .stCheckbox label, .stSlider label, .stTextInput label {
color: #ffffff !important;
font-weight: 500 !important;
font-size: 0.95rem !important;
}
.stSelectbox > div > div {
background-color: #1a1a1a !important;
border: 1px solid #404040 !important;
border-radius: 0.5rem !important;
color: #ffffff !important;
}
/* Text input styling */
.stTextInput > div > div > input {
background-color: #1a1a1a !important;
color: #ffffff !important;
border: 1px solid #404040 !important;
}
/* Checkbox styling */
.stCheckbox > label > div {
background-color: #1a1a1a !important;
border: 1px solid #404040 !important;
}
.stCheckbox > label {
color: #ffffff !important;
}
/* Button styling */
.stButton > button {
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%) !important;
color: white !important;
border: none !important;
border-radius: 0.75rem !important;
padding: 0.75rem 2rem !important;
font-weight: 600 !important;
font-size: 1rem !important;
transition: all 0.2s ease !important;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3) !important;
}
.stButton > button:hover {
transform: translateY(-1px) !important;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3) !important;
}
/* Expander styling */
.streamlit-expanderHeader {
background-color: #1a1a1a !important;
border: 1px solid #404040 !important;
border-radius: 0.5rem !important;
color: #ffffff !important;
font-weight: 600 !important;
}
.streamlit-expanderContent {
background-color: #0a0a0a !important;
border: 1px solid #404040 !important;
border-top: none !important;
border-radius: 0 0 0.5rem 0.5rem !important;
}
/* File uploader styling */
.stFileUploader > label {
color: #ffffff !important;
font-weight: 500 !important;
}
.stFileUploader [data-testid="stFileUploaderDropzone"] {
border: 2px dashed #666666 !important;
border-radius: 0.75rem !important;
background-color: #1a1a1a !important;
}
/* Dataframe styling */
.stDataFrame {
border: 1px solid #404040 !important;
border-radius: 0.5rem !important;
overflow: hidden !important;
}
/* Dataframe table styling */
.stDataFrame table {
background-color: #1a1a1a !important;
color: #ffffff !important;
}
.stDataFrame th {
background-color: #2a2a2a !important;
color: #ffffff !important;
}
.stDataFrame td {
background-color: #1a1a1a !important;
color: #ffffff !important;
}
/* Metric styling */
.metric-container {
background-color: #1a1a1a !important;
border: 1px solid #404040 !important;
border-radius: 0.5rem !important;
padding: 1rem !important;
color: #ffffff !important;
}
/* Info/Warning/Error boxes */
.stAlert {
border-radius: 0.5rem !important;
}
.stInfo {
background-color: #1a237e !important;
border-left: 4px solid #3b82f6 !important;
color: #90caf9 !important;
}
.stSuccess {
background-color: #1b5e20 !important;
border-left: 4px solid #22c55e !important;
color: #a5d6a7 !important;
}
.stWarning {
background-color: #e65100 !important;
border-left: 4px solid #f59e0b !important;
color: #ffcc02 !important;
}
.stError {
background-color: #b71c1c !important;
border-left: 4px solid #ef4444 !important;
color: #ef9a9a !important;
}
/* Custom styled boxes */
.info-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1.5rem;
border-radius: 1rem;
margin: 1rem 0;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
}
.feature-box {
background-color: #1a1a1a;
border: 1px solid #404040;
border-radius: 0.75rem;
padding: 1rem;
margin: 0.5rem 0;
transition: all 0.2s ease;
color: #ffffff;
}
.feature-box:hover {
box-shadow: 0 4px 6px -1px rgba(255, 255, 255, 0.1);
transform: translateY(-1px);
}
/* Sidebar styling */
.css-1d391kg {
background-color: #0a0a0a !important;
}
/* Sidebar content */
.css-1lcbmhc {
background-color: #0a0a0a !important;
}
/* Progress bar */
.stProgress > div > div {
background: linear-gradient(90deg, #3b82f6, #1d4ed8) !important;
}
/* Slider styling */
.stSlider > div > div > div > div {
background-color: #404040 !important;
}
/* Selectbox dropdown */
.stSelectbox > div > div > div {
background-color: #1a1a1a !important;
color: #ffffff !important;
}
/* Remove default margins and improve spacing */
.element-container {
margin-bottom: 1rem !important;
}
/* Tab styling */
.stTabs [data-baseweb="tab-list"] {
background-color: #1a1a1a !important;
}
.stTabs [data-baseweb="tab"] {
background-color: #1a1a1a !important;
color: #ffffff !important;
}
.stTabs [aria-selected="true"] {
background-color: #3b82f6 !important;
color: #ffffff !important;
}
/* Responsive design */
@media (max-width: 768px) {
.main .block-container {
padding-left: 1rem !important;
padding-right: 1rem !important;
}
}
</style>
""", unsafe_allow_html=True)
class ComprehensiveDataPreprocessor:
def __init__(self):
self.report = []
self.preprocessing_choices = {}
self.fitted_transformers = {}
self.data_info = {}
def log_action(self, message):
"""Log preprocessing actions"""
self.report.append(f"{datetime.now().strftime('%H:%M:%S')} - {message}")
def set_preprocessing_choices(self, choices):
"""Set user choices for preprocessing steps"""
self.preprocessing_choices = choices
def load_and_inspect_data(self, file_path):
"""Load data and perform initial inspection"""
try:
if file_path.endswith('.csv'):
df = pd.read_csv(file_path)
elif file_path.endswith(('.xlsx', '.xls')):
df = pd.read_excel(file_path)
else:
raise ValueError("Unsupported file format")
self.data_info = {
'original_shape': df.shape,
'columns': list(df.columns),
'dtypes': dict(df.dtypes),
'missing_values': dict(df.isnull().sum()),
'duplicates': df.duplicated().sum(),
'memory_usage': df.memory_usage(deep=True).sum()
}
self.log_action(f"Loaded data: {df.shape[0]} rows, {df.shape[1]} columns")
return df
except Exception as e:
self.log_action(f"Error loading data: {str(e)}")
return None
def remove_duplicates(self, df):
"""Remove exact duplicates"""
if not self.preprocessing_choices.get('remove_duplicates', False):
return df
initial_count = len(df)
df = df.drop_duplicates()
removed = initial_count - len(df)
if removed > 0:
self.log_action(f"Removed {removed} duplicate rows")
return df
def handle_missing_values_advanced(self, df):
"""Handle missing values with different strategies"""
if not self.preprocessing_choices.get('handle_missing', False):
return df
missing_strategy = self.preprocessing_choices.get('missing_strategy', 'auto')
for col in df.columns:
missing_pct = (df[col].isnull().sum() / len(df)) * 100
if missing_pct == 0:
continue
if missing_pct > 80:
df = df.drop(columns=[col])
self.log_action(f"Dropped column '{col}' - {missing_pct:.1f}% missing")
continue
if df[col].dtype in ['int64', 'float64']:
if missing_strategy == 'mean':
df[col].fillna(df[col].mean(), inplace=True)
elif missing_strategy == 'median':
df[col].fillna(df[col].median(), inplace=True)
elif missing_strategy == 'knn':
try:
imputer = KNNImputer(n_neighbors=5)
df[[col]] = imputer.fit_transform(df[[col]])
except:
df[col].fillna(df[col].median(), inplace=True)
else: # auto
try:
if abs(df[col].skew()) > 1:
df[col].fillna(df[col].median(), inplace=True)
else:
df[col].fillna(df[col].mean(), inplace=True)
except:
df[col].fillna(df[col].median(), inplace=True)
self.log_action(f"Filled missing values in '{col}' using {missing_strategy}")
elif df[col].dtype == 'object':
try:
mode_val = df[col].mode()[0] if not df[col].mode().empty else 'Unknown'
df[col].fillna(mode_val, inplace=True)
except:
df[col].fillna('Unknown', inplace=True)
self.log_action(f"Filled missing categorical values in '{col}'")
return df
def fix_inconsistent_formats(self, df):
"""Fix inconsistent data formats"""
if not self.preprocessing_choices.get('fix_formats', False):
return df
for col in df.columns:
if any(keyword in col.lower() for keyword in ['date', 'time']):
try:
df[col] = pd.to_datetime(df[col], errors='coerce')
self.log_action(f"Standardized date format in '{col}'")
except:
pass
return df
def handle_outliers_advanced(self, df):
"""Handle outliers using different methods"""
if not self.preprocessing_choices.get('handle_outliers', False):
return df
outlier_method = self.preprocessing_choices.get('outlier_method', 'iqr')
numerical_cols = df.select_dtypes(include=[np.number]).columns
for col in numerical_cols:
try:
if outlier_method == 'iqr':
Q1 = df[col].quantile(0.25)
Q3 = df[col].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
outliers = ((df[col] < lower_bound) | (df[col] > upper_bound)).sum()
if outliers > 0:
df[col] = df[col].clip(lower=lower_bound, upper=upper_bound)
self.log_action(f"Capped {outliers} outliers in '{col}' using IQR method")
elif outlier_method == 'zscore':
z_scores = np.abs(stats.zscore(df[col].dropna()))
outliers = (z_scores > 3).sum()
if outliers > 0:
median_val = df[col].median()
df.loc[df[col].index[z_scores > 3], col] = median_val
self.log_action(f"Replaced {outliers} outliers in '{col}' using Z-score method")
except:
continue
return df
def extract_datetime_features(self, df):
"""Extract features from datetime columns"""
if not self.preprocessing_choices.get('datetime_features', False):
return df
datetime_cols = df.select_dtypes(include=['datetime64[ns]']).columns
for col in datetime_cols:
try:
df[f'{col}_year'] = df[col].dt.year
df[f'{col}_month'] = df[col].dt.month
df[f'{col}_day'] = df[col].dt.day
df[f'{col}_dayofweek'] = df[col].dt.dayofweek
df[f'{col}_hour'] = df[col].dt.hour
df[f'{col}_is_weekend'] = (df[col].dt.dayofweek >= 5).astype(int)
self.log_action(f"Extracted datetime features from '{col}'")
except:
continue
return df
def extract_text_features(self, df):
"""Extract features from text columns"""
if not self.preprocessing_choices.get('text_features', False):
return df
text_cols = df.select_dtypes(include=['object']).columns
for col in text_cols[:3]:
try:
if df[col].nunique() / len(df) > 0.5:
df[f'{col}_length'] = df[col].astype(str).str.len()
df[f'{col}_word_count'] = df[col].astype(str).str.split().str.len()
self.log_action(f"Extracted text features from '{col}'")
except:
continue
return df
def create_numeric_interactions(self, df):
"""Create interaction features between numeric variables"""
if not self.preprocessing_choices.get('numeric_interactions', False):
return df
numerical_cols = df.select_dtypes(include=[np.number]).columns[:3]
interaction_count = 0
for i in range(len(numerical_cols)):
for j in range(i+1, min(i+2, len(numerical_cols))):
try:
col1, col2 = numerical_cols[i], numerical_cols[j]
df[f'{col1}_x_{col2}'] = df[col1] * df[col2]
interaction_count += 1
except:
continue
if interaction_count > 0:
self.log_action(f"Created {interaction_count} interaction features")
return df
def apply_transformations(self, df):
"""Apply transformations like log, sqrt"""
if not self.preprocessing_choices.get('apply_transformations', False):
return df
transformation_type = self.preprocessing_choices.get('transformation_type', 'log')
numerical_cols = df.select_dtypes(include=[np.number]).columns
for col in numerical_cols:
try:
if df[col].min() > 0 and df[col].skew() > 1:
if transformation_type == 'log':
df[f'{col}_log'] = np.log1p(df[col])
self.log_action(f"Applied log transformation to '{col}'")
elif transformation_type == 'sqrt':
df[f'{col}_sqrt'] = np.sqrt(df[col])
self.log_action(f"Applied sqrt transformation to '{col}'")
except:
continue
return df
def create_bins(self, df):
"""Create bins for continuous variables"""
if not self.preprocessing_choices.get('create_bins', False):
return df
numerical_cols = df.select_dtypes(include=[np.number]).columns
n_bins = self.preprocessing_choices.get('n_bins', 5)
for col in numerical_cols[:2]:
try:
if df[col].nunique() > 10:
df[f'{col}_binned'] = pd.cut(df[col], bins=n_bins, labels=False)
self.log_action(f"Created {n_bins} bins for '{col}'")
except:
continue
return df
def encode_categorical_advanced(self, df):
"""Encode categorical variables"""
if not self.preprocessing_choices.get('encode_categorical', False):
return df
categorical_cols = df.select_dtypes(include=['object', 'category']).columns
encoding_method = self.preprocessing_choices.get('encoding_method', 'auto')
for col in categorical_cols:
try:
unique_count = df[col].nunique()
if encoding_method == 'auto':
if unique_count == 2:
le = LabelEncoder()
df[col] = le.fit_transform(df[col].astype(str))
self.log_action(f"Label encoded binary column '{col}'")
elif unique_count <= 10:
dummies = pd.get_dummies(df[col], prefix=col, drop_first=True)
df = pd.concat([df, dummies], axis=1)
df = df.drop(columns=[col])
self.log_action(f"One-hot encoded '{col}'")
else:
freq_encoding = df[col].value_counts().to_dict()
df[f'{col}_frequency'] = df[col].map(freq_encoding)
df = df.drop(columns=[col])
self.log_action(f"Frequency encoded '{col}'")
elif encoding_method == 'label':
le = LabelEncoder()
df[col] = le.fit_transform(df[col].astype(str))
self.log_action(f"Label encoded '{col}'")
except:
continue
return df
def apply_scaling(self, df):
"""Apply scaling to numerical features"""
if not self.preprocessing_choices.get('apply_scaling', False):
return df
scaling_method = self.preprocessing_choices.get('scaling_method', 'standard')
numerical_cols = df.select_dtypes(include=[np.number]).columns
# Exclude binary columns
cols_to_scale = []
for col in numerical_cols:
try:
unique_vals = df[col].unique()
if not (len(unique_vals) == 2 and set(unique_vals).issubset({0, 1})):
cols_to_scale.append(col)
except:
continue
if cols_to_scale:
try:
if scaling_method == 'standard':
scaler = StandardScaler()
elif scaling_method == 'minmax':
scaler = MinMaxScaler()
elif scaling_method == 'robust':
scaler = RobustScaler()
df[cols_to_scale] = scaler.fit_transform(df[cols_to_scale])
self.log_action(f"Applied {scaling_method} scaling to {len(cols_to_scale)} columns")
except:
self.log_action(f"Scaling failed, continuing without scaling")
return df
def feature_selection(self, df, target_column=None):
"""Perform feature selection"""
if not self.preprocessing_choices.get('feature_selection', False):
return df
try:
selection_method = self.preprocessing_choices.get('selection_method', 'variance')
if selection_method == 'variance':
selector = VarianceThreshold(threshold=0.01)
numerical_cols = df.select_dtypes(include=[np.number]).columns
if len(numerical_cols) > 0:
selected_features = selector.fit_transform(df[numerical_cols])
selected_cols = numerical_cols[selector.get_support()]
other_cols = df.select_dtypes(exclude=[np.number]).columns
df_selected = pd.concat([
pd.DataFrame(selected_features, columns=selected_cols, index=df.index),
df[other_cols]
], axis=1)
removed_count = len(numerical_cols) - len(selected_cols)
self.log_action(f"Removed {removed_count} low-variance features")
return df_selected
except:
self.log_action("Feature selection failed, continuing with all features")
return df
def dimensionality_reduction(self, df, target_column=None):
"""Apply dimensionality reduction techniques"""
if not self.preprocessing_choices.get('dimensionality_reduction', False):
return df
method = self.preprocessing_choices.get('reduction_method', 'pca')
n_components = self.preprocessing_choices.get('n_components', 10)
# Get numerical columns for reduction
numerical_cols = df.select_dtypes(include=[np.number]).columns.tolist()
if target_column and target_column in numerical_cols:
numerical_cols.remove(target_column)
if len(numerical_cols) < 2:
self.log_action("Insufficient numerical columns for dimensionality reduction")
return df
# Ensure we don't reduce to more components than we have features
n_components = min(n_components, len(numerical_cols))
if len(numerical_cols) > n_components:
try:
# Prepare data for reduction
X_for_reduction = df[numerical_cols].fillna(0)
if method == 'pca':
reducer = PCA(n_components=n_components, random_state=42)
X_reduced = reducer.fit_transform(X_for_reduction)
# Create new DataFrame with PCA components
pca_cols = [f'PCA_{i+1}' for i in range(n_components)]
df_reduced = pd.DataFrame(X_reduced, columns=pca_cols, index=df.index)
self.fitted_transformers['pca_reducer'] = reducer
self.log_action(f"Applied PCA: {len(numerical_cols)} β {n_components} components")
elif method == 'tsne':
# t-SNE parameters
perplexity = self.preprocessing_choices.get('tsne_perplexity', 30)
perplexity = min(perplexity, (len(df) - 1) // 3)
# Limit data size for t-SNE performance
max_samples = min(1000, len(df))
if len(df) > max_samples:
sample_idx = np.random.choice(len(df), max_samples, replace=False)
X_sample = X_for_reduction.iloc[sample_idx]
else:
X_sample = X_for_reduction
reducer = TSNE(n_components=min(n_components, 3), perplexity=perplexity,
random_state=42, max_iter=500)
X_reduced_sample = reducer.fit_transform(X_sample)
# Create components for full dataset
tsne_cols = [f'tSNE_{i+1}' for i in range(X_reduced_sample.shape[1])]
if len(df) > max_samples:
# For large datasets, fill with mean values for non-sampled data
mean_components = X_reduced_sample.mean(axis=0)
X_reduced = np.tile(mean_components, (len(df), 1))
X_reduced[sample_idx] = X_reduced_sample
else:
X_reduced = X_reduced_sample
df_reduced = pd.DataFrame(X_reduced, columns=tsne_cols, index=df.index)
self.log_action(f"Applied t-SNE: {len(numerical_cols)} β {len(tsne_cols)} components")
else: # Fallback to PCA
reducer = PCA(n_components=n_components, random_state=42)
X_reduced = reducer.fit_transform(X_for_reduction)
pca_cols = [f'PCA_{i+1}' for i in range(n_components)]
df_reduced = pd.DataFrame(X_reduced, columns=pca_cols, index=df.index)
self.log_action(f"Applied PCA (fallback): {len(numerical_cols)} β {n_components} components")
# Combine with non-numerical columns and target
other_cols = df.select_dtypes(exclude=[np.number]).columns
df_final = df_reduced.copy()
# Add non-numerical columns
if len(other_cols) > 0:
df_final = pd.concat([df_final, df[other_cols]], axis=1)
# Add target column if specified
if target_column and target_column in df.columns:
df_final[target_column] = df[target_column]
return df_final
except Exception as e:
self.log_action(f"Dimensionality reduction failed: {str(e)}. Returning original data.")
return df
else:
self.log_action(f"Dataset already has {len(numerical_cols)} features, no reduction needed")
return df
def generate_comprehensive_report(self, processed_df):
"""Generate comprehensive preprocessing report"""
report = {
'original_info': self.data_info,
'processed_shape': processed_df.shape,
'processing_steps': self.report,
'fitted_transformers': list(self.fitted_transformers.keys()),
'final_dtypes': dict(processed_df.dtypes),
'final_missing_values': dict(processed_df.isnull().sum()),
'preprocessing_choices': self.preprocessing_choices
}
return report
def process_data(self, file_path, preprocessing_choices, target_column=None):
"""Main comprehensive preprocessing pipeline - returns entire dataset"""
self.set_preprocessing_choices(preprocessing_choices)
# Load data
df = self.load_and_inspect_data(file_path)
if df is None:
return None, None
try:
# Apply preprocessing steps
df = self.remove_duplicates(df)
df = self.handle_missing_values_advanced(df)
df = self.fix_inconsistent_formats(df)
df = self.handle_outliers_advanced(df)
df = self.extract_datetime_features(df)
df = self.extract_text_features(df)
df = self.create_numeric_interactions(df)
df = self.apply_transformations(df)
df = self.create_bins(df)
df = self.encode_categorical_advanced(df)
df = self.apply_scaling(df)
df = self.feature_selection(df, target_column)
df = self.dimensionality_reduction(df, target_column)
# Generate report
report = self.generate_comprehensive_report(df)
self.log_action(f"Processing completed successfully! Final shape: {df.shape}")
return df, report
except Exception as e:
self.log_action(f"Error during processing: {str(e)}")
return None, None
def create_preprocessing_interface_with_explanations():
"""Create interface with detailed explanations for each preprocessing option"""
# Apply custom CSS for better text visibility
add_custom_css()
st.title("π Advanced Data Preprocessing App")
# Enhanced introduction with improved design
st.markdown("""
<div class="info-box">
<h2 style="color: white; margin-top: 0; font-weight: 700;">π― Transform Your Data Into ML-Ready Format</h2>
<p style="font-size: 18px; margin-bottom: 15px; color: white; opacity: 0.95;">
Automatically clean, engineer, and optimize your dataset with professional-grade preprocessing techniques.
Save hours of manual work and ensure your data is ready for machine learning.
</p>
<h3 style="color: white; margin-bottom: 15px;">β¨ Key Features:</h3>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; color: white;">
<div>π€ <strong>Smart Processing:</strong> Intelligent defaults</div>
<div>ποΈ <strong>Full Control:</strong> Customize every step</div>
<div>π <strong>Comprehensive:</strong> End-to-end pipeline</div>
<div>β‘ <strong>Fast Results:</strong> Minutes not hours</div>
</div>
</div>
""", unsafe_allow_html=True)
# File upload section with improved styling
st.markdown("### π Upload Your Dataset")
uploaded_file = st.file_uploader(
"Choose your data file",
type=['csv', 'xlsx', 'xls'],
help="Supported formats: CSV, Excel (.xlsx, .xls). Maximum file size: 200MB"
)
if uploaded_file is None:
st.info("π **Please upload a dataset to begin the preprocessing journey**")
# Show example of what the app can do
with st.expander("π― What can this app do for you?", expanded=True):
st.markdown("""
<div class="feature-box">
<h4>π§Ή Data Cleaning</h4>
<p>β’ Remove duplicates and inconsistencies<br>
β’ Handle missing values intelligently<br>
β’ Fix date formats and data types</p>
</div>
<div class="feature-box">
<h4>βοΈ Feature Engineering</h4>
<p>β’ Extract datetime components<br>
β’ Create text statistics<br>
β’ Generate interaction features</p>
</div>
<div class="feature-box">
<h4>π― ML Preparation</h4>
<p>β’ Encode categorical variables<br>
β’ Scale numerical features<br>
β’ Reduce dimensionality with PCA/t-SNE</p>
</div>
""", unsafe_allow_html=True)
return None
# Initialize variables
df = None
target_column = None
task_type = "exploration"
# Load and preview data
try:
# Load data based on file type
if uploaded_file.name.endswith('.csv'):
df = pd.read_csv(uploaded_file)
elif uploaded_file.name.endswith(('.xlsx', '.xls')):
df = pd.read_excel(uploaded_file)
else:
st.error("β Unsupported file format. Please upload CSV or Excel files.")
return None
if df is None or df.empty:
st.error("β The uploaded file is empty or couldn't be read.")
return None
# Success message
st.success(f"β
**File loaded successfully:** {df.shape[0]:,} rows Γ {df.shape[1]} columns")
# Data preview
with st.expander("π **Data Preview & Information**", expanded=False):
col1, col2 = st.columns(2)
with col1:
st.markdown("**π First 5 Rows:**")
st.dataframe(df.head(), use_container_width=True)
with col2:
st.markdown("**π Data Summary:**")
# Data info
info_data = {
'Column': df.columns[:10], # Show first 10 columns
'Type': [str(dtype) for dtype in df.dtypes[:10]],
'Missing': [df[col].isnull().sum() for col in df.columns[:10]],
'Unique': [df[col].nunique() for col in df.columns[:10]]
}
info_df = pd.DataFrame(info_data)
st.dataframe(info_df, use_container_width=True)
if len(df.columns) > 10:
st.info(f"Showing first 10 columns. Total columns: {len(df.columns)}")
# Target selection and task type
st.markdown("### π― Configure Your Analysis")
col1, col2 = st.columns(2)
with col1:
target_column = st.selectbox(
"π― **Select Target Column** (Optional)",
[None] + list(df.columns),
help="Choose the variable you want to predict. Leave blank for unsupervised learning or data exploration."
)
with col2:
if target_column:
try:
unique_targets = df[target_column].nunique()
if unique_targets < 20:
task_type = st.selectbox(
"π **Task Type**",
["classification", "regression"],
help="**Classification:** Predicting categories (e.g., spam/not spam)\n**Regression:** Predicting continuous values (e.g., price, temperature)"
)
else:
task_type = "regression"
st.info("π **Auto-detected:** Regression task (many unique values)")
except Exception as e:
st.warning(f"β οΈ Could not analyze target column: {str(e)}")
task_type = st.selectbox(
"π **Task Type**",
["classification", "regression"],
help="Choose based on your prediction goal"
)
else:
task_type = st.selectbox(
"π **Analysis Type**",
["exploration", "classification", "regression"],
help="**Exploration:** Data analysis and insights\n**Classification/Regression:** Machine learning preparation"
)
except Exception as e:
st.error(f"β **Error loading file:** {str(e)}")
st.error("Please check if your file is valid and try again.")
return None
# Preprocessing Configuration
st.markdown("### π οΈ **Preprocessing Configuration**")
st.markdown("Select the preprocessing steps you want to apply:")
# Initialize variables with defaults
preprocessing_vars = {}
# Data Cleaning Section
with st.expander("π§Ή **Data Cleaning** - Essential quality improvements", expanded=True):
st.markdown("""
<div style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
padding: 15px; border-radius: 8px; margin-bottom: 15px; color: #92400e;">
<strong>π― Purpose:</strong> Clean and standardize your data for better quality and consistency.<br>
<strong>π‘ Recommendation:</strong> Always enable these steps for any dataset.
</div>
""", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
preprocessing_vars['remove_duplicates'] = st.checkbox(
"π **Remove Duplicate Rows**",
value=True,
help="Removes identical rows that could skew your analysis"
)
preprocessing_vars['handle_missing'] = st.checkbox(
"π³οΈ **Handle Missing Values**",
value=True,
help="Essential: Most ML algorithms can't handle missing data"
)
with col2:
preprocessing_vars['fix_formats'] = st.checkbox(
"π
**Standardize Data Formats**",
value=True,
help="Fixes dates, text cases, and ensures consistent data types"
)
preprocessing_vars['handle_outliers'] = st.checkbox(
"π **Handle Outliers**",
value=True,
help="Manages extreme values that could hurt model performance"
)
# Sub-options for data cleaning
if preprocessing_vars.get('handle_missing', False):
preprocessing_vars['missing_strategy'] = st.selectbox(
"**Missing Value Strategy:**",
["auto", "mean", "median", "knn"],
help="**Auto:** Smart choice based on data distribution\n**Mean/Median:** Simple statistical filling\n**KNN:** Advanced neighbor-based filling",
index=0
)
else:
preprocessing_vars['missing_strategy'] = "auto"
if preprocessing_vars.get('handle_outliers', False):
preprocessing_vars['outlier_method'] = st.selectbox(
"**Outlier Handling Method:**",
["iqr", "zscore"],
help="**IQR:** Most robust method (recommended)\n**Z-Score:** Statistical approach",