-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathml_pipeline.py
More file actions
1956 lines (1666 loc) · 88.9 KB
/
ml_pipeline.py
File metadata and controls
1956 lines (1666 loc) · 88.9 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
"""
ML Pipeline - Fully Integrated Module
Supports: Supervised (Regression, Classification) + Unsupervised (Clustering)
FIXES APPLIED:
1. Winsorizer fitted AFTER feature engineering (includes engineered cols)
2. get_data() returns actual target
3. TargetProcessor boolean mask uses .values to prevent index misalignment
4. _detect_outliers parameter renamed from learning_type → method
5. Silent outlier skip now logs a warning
6. save_processed_data guards against empty dirname
7. Removed _normalize_column_mapping entirely
8. Removed all Apriori/Association logic
EXECUTION ORDER (fit_transform):
-1. Target preprocessing (may drop rows)
0. Drop columns
1. Missing value imputation
2. Feature engineering ← BEFORE outliers
3. Outlier handling ← AFTER feature engineering (fitted on all current numeric cols)
4. Categorical encoding
5. Feature transformation (log, yeo-johnson)
6. Scaling
7. Feature selection
"""
# ==============================================================================
# SECTION 0: IMPORTS
# ==============================================================================
import pandas as pd
import numpy as np
import json
import logging
import time
import os
import warnings
from dataclasses import dataclass, asdict
from typing import Dict, List, Any, Optional, Tuple
from enum import Enum
from pathlib import Path
from dotenv import load_dotenv, set_key
from groq import Groq
from feature_engine.imputation import MeanMedianImputer, CategoricalImputer
from feature_engine.encoding import OneHotEncoder, CountFrequencyEncoder
from feature_engine.outliers import Winsorizer
from feature_engine.selection import DropConstantFeatures, DropDuplicateFeatures
from feature_engine.transformation import LogTransformer, YeoJohnsonTransformer
from feature_engine.wrappers import SklearnTransformerWrapper
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler, LabelEncoder
warnings.filterwarnings('ignore')
load_dotenv()
# ==============================================================================
# SECTION 1: LOGGING
# ==============================================================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s"
)
logger = logging.getLogger(__name__)
# ==============================================================================
# SECTION 2: ENUMS & CORE MODELS
# ==============================================================================
class MLType(Enum):
SUPERVISED = "Supervised"
UNSUPERVISED = "Unsupervised"
class LearningType(Enum):
REGRESSION = "Regression"
CLASSIFICATION = "Classification"
CLUSTERING = "Clustering"
class ProcessingType(Enum):
TRAINING_ONLY = "Training-Alone"
PREPROCESS_TRAIN = "Pre-Processes+Training"
class Hardware(Enum):
CPU = "CPU"
GPU = "GPU"
HYBRID = "Hybrid"
@dataclass
class InputConfiguration:
project_name: str
file_name: str
ml_type: MLType
learning_type: LearningType
processing_type: ProcessingType
llm_name: str
target_column: Optional[str] = None
index_column: Optional[str] = None
output_folder: Optional[str] = None
acceleration_hardware: Hardware = Hardware.CPU
test_size: Optional[float] = 0.2
hyper_parameter_tuning: bool = False
def __post_init__(self):
if self.ml_type == MLType.SUPERVISED and not self.target_column:
raise ValueError("target_column is required for supervised learning")
def to_dict(self):
return {
'project_name': self.project_name,
'file_name': self.file_name,
'ml_type': self.ml_type.value,
'learning_type': self.learning_type.value,
'processing_type': self.processing_type.value,
'llm_name': self.llm_name,
'target_column': self.target_column,
'index_column': self.index_column,
'output_folder': self.output_folder,
'acceleration_hardware': self.acceleration_hardware.value,
'test_size': self.test_size,
'hyper_parameter_tuning': self.hyper_parameter_tuning,
}
@dataclass
class DataAnalysisReport:
"""Comprehensive data analysis report."""
shape: Tuple[int, int]
dtypes: Dict[str, str]
missing_values: Dict[str, int]
missing_percentage: Dict[str, float]
numerical_stats: Dict[str, Dict]
categorical_stats: Dict[str, Dict]
outliers_detected: Dict[str, int]
correlations: Dict[str, float]
data_quality_score: float
target_column: Optional[str]
data_quality_metrics: Dict[str, Any]
ml_type: MLType
learning_type: LearningType
def __iter__(self):
return iter(self.__dict__.items())
def to_dict(self):
d = asdict(self)
d["ml_type"] = self.ml_type.name
d["learning_type"] = self.learning_type.name
return d
class LLMConfiguration:
def __init__(self, model_name: Optional[str] = None, api_key: Optional[str] = None):
load_dotenv()
self.model_name = model_name or os.getenv("LLM_MODEL_NAME")
self.api_key = api_key or os.getenv("LLM_API_KEY")
if not self.api_key:
raise ValueError("API key not provided and not found in .env")
self._save_to_env()
def _save_to_env(self):
set_key(".env", "LLM_MODEL_NAME", self.model_name)
set_key(".env", "LLM_API_KEY", self.api_key)
class ProjectMetadata:
def __init__(self, project_name: str, output_folder: str):
self.project_name = project_name
self.output_folder = output_folder
self.metadata_file = Path(output_folder) / "metadata.json"
def save(self, config: InputConfiguration, status: str = "training"):
metadata = {
"project_name": self.project_name,
"created_at": str(Path(self.output_folder).stat().st_ctime),
"status": status,
"config": config.to_dict(),
"models": [],
"evaluation_scores": None,
"best_model": None,
}
self.metadata_file.write_text(json.dumps(metadata, indent=2))
def load(self):
if self.metadata_file.exists():
return json.loads(self.metadata_file.read_text())
return None
def update(self, **kwargs):
metadata = self.load() or {}
metadata.update(kwargs)
self.metadata_file.write_text(json.dumps(metadata, indent=2))
# ==============================================================================
# SECTION 3: COGNITIVE ENGINE (LLM caller)
# ==============================================================================
client = Groq(
api_key=os.getenv("LLM_API_KEY"),
max_retries=0 # disable Groq automatic retry
)
def chat_llm(system_instructions: str,
user_input: str,
max_retries: int = 2) -> dict:
"""
Fast LLM call with minimal retry delay.
"""
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model=os.getenv("LLM_MODEL_NAME"),
messages=[
{"role": "system", "content": system_instructions},
{"role": "user", "content": user_input},
],
temperature=0.2,
response_format={"type": "json_object"},
stream=False,
timeout=10 # fail fast
)
content = response.choices[0].message.content
if not content:
return {}
return json.loads(content)
except json.JSONDecodeError:
logger.error("LLM returned invalid JSON")
return {}
except Exception as e:
err = str(e).lower()
if "429" in err or "rate" in err:
wait = 1.5 # short wait
logger.warning(f"Rate limit. Retrying in {wait}s")
time.sleep(wait)
else:
logger.error(f"LLM error: {e}")
return {}
return {}
# ==============================================================================
# SECTION 4: PROMPTS — paste your actual prompts inside the triple-quotes
# ==============================================================================
DATATYPE_SELECTION_SYSTEM_PROMPT = """You are an AI programming assistant, only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.
### Instruction:
You are an expert pandas data analyst. Your task is to infer the most appropriate pandas data type (dtype) for each column in a given dataset preview.
**CRITICAL RULES:**
1. **PRESERVE EXACT COLUMN NAMES** - The keys in "column_dtypes" MUST match the keys in "summary_stats" EXACTLY, character by character. DO NOT add/remove spaces, change parentheses/hyphens, modify capitalization, or alter formatting.
2. Only choose dtypes from: ["int8","int16","int32","int64","uint8","uint16","uint32","uint64","float16","float32","float64","bool","boolean","object","string","category","datetime64[ns]","timedelta64[ns]","Int8","Int16","Int32","Int64"].
3. Selection criteria: Integers use smallest sufficient type (e.g., int8 for -128 to 127); nullable for missings (Int8+). Floats: float64 default. Booleans: bool/boolean. Strings: string (text), category (low cardinality <50% unique). Dates: datetime64[ns].
4. **OUTPUT ONLY VALID JSON** in this exact format: {"column_dtypes": {"exact_column_name_1": "dtype", "exact_column_name_2": "dtype"}}
**ANALYZE THE INPUT DATA:** Input has columns_list (exact names), data_preview (first 10 rows), summary_stats (uniques, missings, ranges, sample_values).
**EXAMPLE 1 - Customer Data with Special Characters:**
INPUT:
{
"columns_list": ["customer_id", "full name", "age (years)", "is_active", "gender"],
"data_preview": [
{"customer_id": 1, "full name": "Alice", "age (years)": 23, "is_active": true, "gender": "Female"},
{"customer_id": 2, "full name": "Bob", "age (years)": 30, "is_active": false, "gender": "Male"}
],
"summary_stats": {
"customer_id": {"dtype": "int64", "missing_values": 0, "unique_values": 1000},
"full name": {"dtype": "object", "missing_values": 0, "unique_values": 950},
"age (years)": {"dtype": "int64", "missing_values": 0, "unique_values": 60, "min": 18, "max": 75},
"is_active": {"dtype": "bool", "missing_values": 0, "unique_values": 2},
"gender": {"dtype": "object", "missing_values": 0, "unique_values": 3}
}
}
OUTPUT:
{"column_dtypes": {"customer_id": "int64", "full name": "string", "age (years)": "int8", "is_active": "bool", "gender": "category"}}
**EXAMPLE 2 - Iris Dataset with Measurements:**
INPUT:
{
"columns_list": ["Unnamed: 0", "sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)", "target"],
"data_preview": [
{"Unnamed: 0": 0, "sepal length (cm)": 5.1, "sepal width (cm)": 3.5, "petal length (cm)": 1.4, "petal width (cm)": 0.2, "target": 0},
{"Unnamed: 0": 1, "sepal length (cm)": 4.9, "sepal width (cm)": 3.0, "petal length (cm)": 1.4, "petal width (cm)": 0.2, "target": 0}
],
"summary_stats": {
"Unnamed: 0": {"dtype": "int64", "missing_values": 0, "unique_values": 150, "min": 0, "max": 149},
"sepal length (cm)": {"dtype": "float64", "missing_values": 0, "unique_values": 35, "min": 4.3, "max": 7.9},
"sepal width (cm)": {"dtype": "float64", "missing_values": 0, "unique_values": 23, "min": 2.0, "max": 4.4},
"petal length (cm)": {"dtype": "float64", "missing_values": 0, "unique_values": 43, "min": 1.0, "max": 6.9},
"petal width (cm)": {"dtype": "float64", "missing_values": 0, "unique_values": 22, "min": 0.1, "max": 2.5},
"target": {"dtype": "int64", "missing_values": 0, "unique_values": 3, "min": 0, "max": 2, "likely_categorical": true}
}
}
OUTPUT:
{"column_dtypes": {"Unnamed: 0": "int64", "sepal length (cm)": "float64", "sepal width (cm)": "float64", "petal length (cm)": "float64", "petal width (cm)": "float64", "target": "int8"}}
**EXAMPLE 3 - Sales Data with Mixed Types:**
INPUT:
{
"columns_list": ["order-id", "product_name", "price ($)", "quantity", "order date", "shipped?"],
"data_preview": [
{"order-id": 1001, "product_name": "Laptop", "price ($)": 899.99, "quantity": 2, "order date": "2024-01-15", "shipped?": true},
{"order-id": 1002, "product_name": "Mouse", "price ($)": 24.99, "quantity": 5, "order date": "2024-01-16", "shipped?": false}
],
"summary_stats": {
"order-id": {"dtype": "int64", "missing_values": 0, "unique_values": 500, "min": 1001, "max": 1500},
"product_name": {"dtype": "object", "missing_values": 0, "unique_values": 50},
"price ($)": {"dtype": "float64", "missing_values": 0, "unique_values": 200, "min": 9.99, "max": 2999.99},
"quantity": {"dtype": "int64", "missing_values": 0, "unique_values": 20, "min": 1, "max": 100},
"order date": {"dtype": "object", "missing_values": 0, "unique_values": 365, "sample_values": ["2024-01-15", "2024-01-16", "2024-01-17"]},
"shipped?": {"dtype": "bool", "missing_values": 0, "unique_values": 2}
}
}
OUTPUT:
{"column_dtypes": {"order-id": "int64", "product_name": "category", "price ($)": "float64", "quantity": "int8", "order date": "datetime64[ns]", "shipped?": "bool"}}
**VERIFICATION CHECKLIST:** Before output: ✓ Keys match summary_stats exactly. ✓ No extra spaces/special char changes. ✓ Dtypes from allowed list.
Now analyze the provided input and output ONLY the JSON with column_dtypes.
### Response:
"""
SUPERVISED_COLUMN_SELECTION_SYSTEM_PROMPT = """You are an AI programming assistant, only answer questions related to computer science and supervised machine learning preprocessing. ### Instruction: You are an expert Feature Engineer and Data Scientist. Receive dataset info and produce a preprocessing/feature engineering plan specifically for **supervised ML tasks** (classification or regression). **CRITICAL RULES:**
1. OUTPUT **ONLY VALID JSON**. No extra text.
2. Reference only existing columns.
3. Use stats: missing_percentage, outliers_detected, correlations, numerical_stats, categorical_stats, target_column.
4. Drop IDs/unique indices always.
5. Allowed options: Missing ["drop","median","mode","forward_fill","backward_fill"];
Outliers ["winsorize","clip","remove"];
Categorical ["onehot","frequency","label","target"];
Scaling ["standard","minmax","robust"];
Transform ["log","sqrt","boxcox","yeo-johnson"].
6. No repeated keys; balanced JSON.
**INPUT STRUCTURE:** columns (name->dtype),
first_5_rows (samples), column_names, shape, missing_values/percentage, outliers_detected, correlations, numerical_stats, categorical_stats, target_column, data_quality_metrics.
**REQUIRED OUTPUT JSON SCHEMA:**
{ "columns_to_drop": { "column_list": ["col1", "col2"], "reasons": { "col1": ["reason1", "reason2"], "col2": ["reason1"] } }, "columns_to_keep": { "column_list": ["col3", "col4"], "details": { "col3": { "reason": "why keep this", "pipeline_recommendation": ["median", "standard"], "priority": "high|medium|low", "confidence": 0.9, "evidence": { "missing_pct": 5.2, "unique_count": 45, "dtype": "float64", "outliers": 3, "corr_with_target": 0.45 } } } }, "feature_engineering_suggestions": [ { "new_feature": "feature_name", "description": "what it represents", "source_columns": ["col1", "col2"], "transformation": ["df['new_feature'] = df['col1'] + df['col2']"], "expected_type": "numeric|categorical", "expected_impact": "high|medium|low", "confidence": 0.8, "risk_assessment": "leakage risk if any" } ], "pipeline_recommendation": { "step_1_missing_values": { "numeric_strategy": "median", "categorical_strategy": "mode", "columns_affected": ["col1", "col2"] }, "step_2_outliers": { "method": "winsorize", "columns_affected": ["col3"], "parameters": {"capping_method": "iqr", "fold": 1.5} }, "step_3_encoding": { "onehot_columns": ["col4"], "frequency_columns": ["col5"], "parameters": {"drop": "first"} }, "step_4_transformation": { "log_transform": ["col6"], "yeo_johnson": ["col7"] }, "step_5_scaling": { "method": "standard", "columns": ["col6", "col7", "col8"] }, "step_6_feature_selection": { "drop_correlated": true, "correlation_threshold": 0.95, "drop_constant": true } }, "summary": { "original_features": 12, "recommended_features": 15, "features_dropped": 3, "new_features_created": 6, "expected_model_improvement": "Brief explanation", "key_insights": ["insight1", "insight2"] } } **EXAMPLE - Diabetes Dataset (Supervised Classification):** INPUT: { "columns": { "Pregnancies": "int64", "Glucose": "int64", "BloodPressure": "int64", "SkinThickness": "int64", "Insulin": "int64", "BMI": "float64", "DiabetesPedigreeFunction": "float64", "Age": "int64", "Outcome": "int64" }, "shape": [768, 9], "missing_percentage": {"Glucose": 0.0, "BloodPressure": 0.0, "SkinThickness": 29.0, "Insulin": 49.0, "BMI": 0.0}, "numerical_stats": {"Glucose": {"mean": 120.9, "std": 31.9}, "BMI": {"mean": 32.0, "std": 7.9}}, "categorical_stats": {"Outcome": {"unique_values": 2}}, "correlations": {"Glucose_vs_Outcome": 0.47, "BMI_vs_Outcome": 0.17}, "outliers_detected": {"Glucose": 5, "BMI": 3}, "target_column": "Outcome" } OUTPUT: { "columns_to_drop": { "column_list": ["Insulin", "SkinThickness"], "reasons": { "Insulin": ["49% missing values, unreliable feature"], "SkinThickness": ["29% missing values, noisy measurements"] } }, "columns_to_keep": { "column_list": ["Pregnancies", "Glucose", "BloodPressure", "BMI", "DiabetesPedigreeFunction", "Age"], "details": { "Glucose": { "reason": "strong correlation with outcome", "recommended_preprocessing": ["median", "standard"], "priority": "high", "confidence": 0.95, "evidence": { "missing_pct": 0.0, "outliers": 5, "corr_with_target": 0.47 } }, "BMI": { "reason": "moderate correlation with outcome", "recommended_preprocessing": ["median", "standard"], "priority": "medium", "confidence": 0.8, "evidence": { "missing_pct": 0.0, "outliers": 3, "corr_with_target": 0.17 } }, "Pregnancies": { "reason": "relevant demographic factor", "recommended_preprocessing": ["median", "standard"], "priority": "medium", "confidence": 0.75, "evidence": { "missing_pct": 0.0, "unique_count": 17, "dtype": "int64", "outliers": 0, "corr_with_target": 0.22 } }, "BloodPressure": { "reason": "physiological indicator", "recommended_preprocessing": ["median", "standard"], "priority": "low", "confidence": 0.7, "evidence": { "missing_pct": 0.0, "outliers": 2, "corr_with_target": 0.07 } }, "DiabetesPedigreeFunction": { "reason": "genetic risk factor", "recommended_preprocessing": ["median", "standard"], "priority": "medium", "confidence": 0.8, "evidence": { "missing_pct": 0.0, "outliers": 4, "corr_with_target": 0.17 } }, "Age": { "reason": "age-related risk", "recommended_preprocessing": ["median", "standard"], "priority": "medium", "confidence": 0.85, "evidence": { "missing_pct": 0.0, "outliers": 1, "corr_with_target": 0.24 } } } }, "feature_engineering_suggestions": [ { "new_feature": "Age_BMI_Ratio", "description": "BMI normalized by Age", "source_columns": ["Age", "BMI"], "transformation": ["df['Age_BMI_Ratio'] = df['BMI']/df['Age']"], "expected_type": "numeric", "expected_impact": "medium", "confidence": 0.8, "risk_assessment": "no leakage risk" }, { "new_feature": "Glucose_Age_Interaction", "description": "Interaction between Glucose and Age", "source_columns": ["Glucose", "Age"], "transformation": ["df['Glucose_Age_Interaction'] = df['Glucose'] * df['Age']"], "expected_type": "numeric", "expected_impact": "high", "confidence": 0.85, "risk_assessment": "low risk of overfitting" } ], "pipeline_recommendation": { "step_1_missing_values": { "numeric_strategy": "median", "categorical_strategy": "mode", "columns_affected": ["Glucose", "BloodPressure", "BMI", "DiabetesPedigreeFunction", "Age"] }, "step_2_outliers": { "method": "winsorize", "columns_affected": ["Glucose", "BMI"], "parameters": {"capping_method": "iqr", "fold": 1.5} }, "step_3_encoding": { "onehot_columns": [], "frequency_columns": [], "parameters": {"drop": "first"} }, "step_4_transformation": { "log_transform": ["DiabetesPedigreeFunction"], "yeo_johnson": ["BMI"] }, "step_5_scaling": { "method": "standard", "columns": ["Pregnancies", "Glucose", "BloodPressure", "BMI", "DiabetesPedigreeFunction", "Age", "Age_BMI_Ratio", "Glucose_Age_Interaction"] }, "step_6_feature_selection": { "drop_correlated": true, "correlation_threshold": 0.95, "drop_constant": true } }, "summary": { "original_features": 9, "recommended_features": 8, "features_dropped": 2, "new_features_created": 2, "expected_model_improvement": "Improved model accuracy by removing sparse features and adding interaction terms for better prediction of diabetes outcome.", "key_insights": ["Glucose is the strongest predictor", "BMI and Age show moderate correlations", "Insulin and SkinThickness are unreliable due to high missing values", "New features like Age_BMI_Ratio may capture non-linear relationships"] } } **IMPORTANT:** Analyze the ACTUAL input dataset provided, not the Diabetes example. Output ONLY valid JSON. ### Response:
"""
CLUSTERING_COLUMN_SELECTION_SYSTEM_PROMPT = """
You are an AI programming assistant, utilizing the only answer questions related to unsupervised learning (clustering).
### Instruction:
You are an expert Data Scientist. Receive dataset info and produce a preprocessing plan for **clustering tasks**.
**CRITICAL RULES:**
1. OUTPUT **ONLY VALID JSON**. No extra explanatory text.
2. Reference only existing columns from the dataset.
3. Use dataset stats: missing_percentage, outliers_detected, correlations, numerical_stats, categorical_stats.
4. Always drop IDs, unique identifiers, or constant features.
5. Features should NOT be dropped unless:
- They have >60% missing values, OR
- They are irrelevant identifiers, OR
- They provide no variance (constant values).
6. Outliers should be **treated** (winsorize, clip, robust scaling) instead of dropping features.
7. Scaling is **mandatory** for clustering, since distance metrics are sensitive to feature magnitudes.
8. Skewed features should be log/yeo-johnson transformed before scaling.
9. Allowed preprocessing options:
- Missing: ["drop","median","mode","forward_fill","backward_fill"]
- Outliers: ["winsorize","clip","remove"]
- Categorical encoding: ["onehot","frequency","label"]
- Scaling: ["standard","minmax","robust"]
- Transformations: ["log","sqrt","boxcox","yeo-johnson"]
10. Do not repeat keys in JSON. Maintain consistency across sections.
11. If a column is dropped, it must not appear in pipeline steps.
**INPUT STRUCTURE:**
{
"columns": { "col1": "dtype", "col2": "dtype" },
"first_5_rows": {...},
"column_names": [...],
"shape": [rows, cols],
"missing_values": {...},
"missing_percentage": {...},
"outliers_detected": {...},
"correlations": {...},
"numerical_stats": {...},
"categorical_stats": {...},
"data_quality_metrics": {...}
}
**REQUIRED OUTPUT JSON SCHEMA:**
{
"columns_to_drop": {
"column_list": ["col1"],
"reasons": { "col1": ["reason1","reason2"] }
},
"columns_to_keep": {
"column_list": ["col2","col3"],
"details": {
"col2": {
"reason": "why keep this",
"recommended_preprocessing": ["standard"],
"priority": "high|medium|low",
"confidence": 0.9,
"evidence": {
"missing_pct": 0,
"unique_count": 45,
"dtype": "float64",
"outliers": 3
}
}
}
},
"feature_engineering_suggestions": [
{
"new_feature": "feature_name",
"description": "what it represents",
"source_columns": ["col2","col3"],
"transformation": ["df['feature_name'] = df['col2']/df['col3']"],
"expected_type": "numeric",
"expected_impact": "medium",
"confidence": 0.8,
"risk_assessment": "any risks"
}
],
"pipeline_recommendation": {
"step_1_missing_values": {
"numeric_strategy": "median",
"categorical_strategy": "mode",
"columns_affected": ["col2","col3"]
},
"step_2_outliers": {
"method": "winsorize",
"columns_affected": ["col4"],
"parameters": {"capping_method": "iqr","fold":1.5}
},
"step_3_encoding": {
"onehot_columns": ["col5"],
"frequency_columns": [],
"parameters": {"drop":"first"}
},
"step_4_transformation": {
"log_transform": ["col6"],
"yeo_johnson": ["col7"]
},
"step_5_scaling": {
"method": "standard",
"columns": ["col2","col3","col6","col7"]
},
"step_6_feature_selection": {
"drop_correlated": true,
"correlation_threshold": 0.95,
"drop_constant": true
}
},
"summary": {
"original_features": 12,
"recommended_features": 14,
"features_dropped": 2,
"new_features_created": 4,
"expected_model_improvement": "Better cluster separation through normalization and ratio features",
"key_insights": ["insight1","insight2"]
}
}
**IMPORTANT:** Analyze the ACTUAL input dataset provided, not the Mall Customers example. Output ONLY valid JSON.
### Response:
"""
AUTOML_EVALUATION_SYSTEM_PROMPT = """You are an AI programming assistant, only answer questions related to machine learning and AutoML model evaluation. For politically sensitive questions, security and privacy issues, and other non-ML questions, you will refuse to answer.
### Instruction:
You are an expert in AutoML and machine learning model evaluation. Your task is to analyze the summary of multiple trained models and provide actionable insights.
**CRITICAL RULES:**
1. Only analyze the models provided in the input JSON. Do not assume or fabricate other models.
2. Focus on evaluation metrics (accuracy, F1-score, RMSE, etc.), training vs validation performance, and hyperparameters.
3. Identify overfitting or underfitting based on train/validation metrics.
4. Suggest improvements in model choice, hyperparameters, or training strategy if needed.
5. **OUTPUT ONLY VALID JSON** in this exact format:
{
"best_model": "model_name_or_id",
"analysis": "brief explanation of model performance, overfitting/underfitting",
"recommendations": "suggested improvements or hyperparameter tuning advice"
}
**ANALYZE THE INPUT DATA:** Input will include a JSON summary of trained models with fields like: model_name, train_score, val_score, hyperparameters, fit_time, etc.
**EXAMPLE 1 - Classification Models Summary:**
INPUT:
{
"models": [
{"model_name": "RandomForest_1", "train_score": 0.98, "val_score": 0.88, "hyperparameters": {"n_estimators": 100, "max_depth": 10}},
{"model_name": "XGBoost_1", "train_score": 0.92, "val_score": 0.90, "hyperparameters": {"learning_rate": 0.1, "n_estimators": 200}}
]
}
OUTPUT:
{
"best_model": "XGBoost_1",
"analysis": "RandomForest_1 shows overfitting (train_score much higher than val_score). XGBoost_1 has balanced train and val scores.",
"recommendations": "Consider tuning RandomForest_1 max_depth or using regularization. XGBoost_1 is well-configured, but slight learning_rate adjustment could improve further."
}
**EXAMPLE 2 - Regression Models Summary:**
INPUT:
{
"models": [
{"model_name": "LinearRegression_1", "train_score": 0.75, "val_score": 0.73, "hyperparameters": {}},
{"model_name": "GradientBoosting_1", "train_score": 0.95, "val_score": 0.78, "hyperparameters": {"n_estimators": 150, "learning_rate": 0.05}}
]
}
OUTPUT:
{
"best_model": "LinearRegression_1",
"analysis": "GradientBoosting_1 is overfitting heavily (train_score >> val_score). LinearRegression_1 has consistent train and val scores.",
"recommendations": "For GradientBoosting_1, reduce n_estimators or increase regularization. LinearRegression_1 is stable, but consider feature engineering for improvement."
}
**VERIFICATION CHECKLIST:** Before output: ✓ JSON keys must be exactly 'best_model', 'analysis', 'recommendations'. ✓ Do not add extra fields. ✓ Base analysis only on input models.
Now analyze the provided input and output ONLY the JSON with the evaluation.
"""
# ==============================================================================
# SECTION 5: DATAFRAME PLACEHOLDER STORE
# ==============================================================================
# Drop any DataFrame you want to test into this dict.
# Keys are human-readable labels; values start as None — fill them in.
#
# Usage:
# df = load_df("boston", "Datasets/boston_house.csv")
# df = load_df("iris", "Datasets/iris.parquet") # parquet auto-detected
#
# Then pass _DF_STORE["boston"] wherever a df argument is needed.
# ==============================================================================
_DF_STORE: Dict[str, Optional[pd.DataFrame]] = {
# ── Regression ────────────────────────────────────────────────────────────
"boston": None, # load_df("boston", "Datasets/boston_house.csv")
"california": None, # load_df("california", "Datasets/california_housing.csv")
"diabetes": None, # load_df("diabetes", "Datasets/diabetes.csv")
# ── Classification ────────────────────────────────────────────────────────
"iris": None, # load_df("iris", "Datasets/iris.csv")
"wine": None, # load_df("wine", "Datasets/wine_balanced.csv")
"file": None, # load_df("file", "Datasets/file.csv")
# ── Clustering ────────────────────────────────────────────────────────────
"mall": None, # load_df("mall", "Datasets/mall_customers.csv")
}
def load_df(key: str, filepath: str, **read_kwargs) -> pd.DataFrame:
"""
Load a file into _DF_STORE and return the DataFrame.
Supports .csv, .parquet, .xlsx / .xls.
"""
ext = Path(filepath).suffix.lower()
if ext == ".parquet":
df = pd.read_parquet(filepath, **read_kwargs)
elif ext in (".csv", ".txt"):
df = pd.read_csv(filepath, **read_kwargs)
elif ext in (".xlsx", ".xls"):
df = pd.read_excel(filepath, **read_kwargs)
else:
raise ValueError(f"Unsupported file extension: {ext}")
_DF_STORE[key] = df
logger.info(f"Loaded '{key}': {df.shape}")
return df
# ==============================================================================
# SECTION 6: INTELLIGENT DATA ANALYZER
# ==============================================================================
class IntelligentDataAnalyzer:
"""
LLM-powered data analyzer for automated preprocessing recommendations.
Supports: Regression, Classification, Clustering.
"""
def __init__(self, ipc: InputConfiguration):
self.ml_type = ipc.ml_type
self.learning_type = ipc.learning_type
self.target_column = ipc.target_column
self.index_column = ipc.index_column
# ------------------------------------------------------------------
def analyze_dataframe(self, df: pd.DataFrame) -> Tuple[DataAnalysisReport, Dict[str, Any]]:
if df.empty:
raise ValueError("Input dataframe is empty")
logger.info(
f"Starting analysis — ML: {self.ml_type.value}, Task: {self.learning_type.value}"
)
logger.info("Step 1: Generating dataset summary…")
summary = self.dataset_summary(df)
logger.info("Step 2: Assigning data types via LLM…")
df = self._data_type_assignment(df, summary)
logger.info("Step 3: Preparing feature analysis…")
if self.ml_type == MLType.SUPERVISED and self.target_column:
if self.target_column not in df.columns:
raise ValueError(
f"Target column '{self.target_column}' not found in dataframe"
)
feature_df = df.drop(columns=[self.target_column])
else:
feature_df = df
logger.info("Step 4: Analysing features…")
report = self._build_report(feature_df, self.target_column)
logger.info("Step 5: Getting preprocessing recommendations…")
preprocessing_config = self._get_llm_preprocessing_suggestion(df, report)
return report, preprocessing_config
# ------------------------------------------------------------------
def dataset_summary(self, df: pd.DataFrame, sample_values: int = 5) -> Dict[str, Any]:
stats_df = df.describe(include="all").transpose()
stats = stats_df.fillna("").to_dict()
columns_info = {}
for col in df.columns:
col_data = df[col]
col_info: Dict[str, Any] = {
"dtype": str(col_data.dtype),
"missing_values": int(col_data.isnull().sum()),
"missing_percentage": float((col_data.isnull().sum() / len(df)) * 100),
"unique_values": int(col_data.nunique()),
"sample_values": col_data.dropna().unique()[:sample_values].tolist(),
}
if pd.api.types.is_numeric_dtype(col_data):
col_info.update({
"min": float(col_data.min()) if not col_data.isnull().all() else None,
"max": float(col_data.max()) if not col_data.isnull().all() else None,
"mean": float(col_data.mean()) if not col_data.isnull().all() else None,
"std": float(col_data.std()) if not col_data.isnull().all() else None,
"median": float(col_data.median()) if not col_data.isnull().all() else None,
"variance": float(col_data.var()) if not col_data.isnull().all() else None,
"likely_categorical": col_data.nunique() < 20,
})
else:
mode_val = col_data.mode().iloc[0] if not col_data.mode().empty else None
col_info["most_frequent"] = str(mode_val) if mode_val is not None else None
col_info["value_counts"] = {
str(k): int(v) for k, v in col_data.value_counts().head(10).items()
}
columns_info[col] = col_info
return {
"stats": stats,
"columns": columns_info,
"rows": len(df),
"columns_count": len(df.columns),
"memory_usage_mb": float(df.memory_usage(deep=True).sum() / 1024 ** 2),
}
# ------------------------------------------------------------------
def _data_type_assignment(self, df: pd.DataFrame, summary: Dict[str, Any]) -> pd.DataFrame:
"""Use LLM to assign correct dtypes. Direct column mapping only."""
input_data = {
"columns_list": df.columns.tolist(),
"data_preview": df.head(5).to_dict(orient="records"),
"summary_stats": summary["columns"],
}
result = chat_llm(DATATYPE_SELECTION_SYSTEM_PROMPT, json.dumps(input_data, indent=2))
if not result or "column_dtypes" not in result:
logger.warning("Datatype assignment failed — keeping original dtypes.")
return df
# Only map columns that actually exist (normalization handled externally)
valid_dtypes = {
col: dtype
for col, dtype in result["column_dtypes"].items()
if col in df.columns
}
return df.astype(valid_dtypes, errors="ignore")
# ------------------------------------------------------------------
def _build_report(self, feature_df: pd.DataFrame,
target_column: Optional[str]) -> DataAnalysisReport:
shape = feature_df.shape
dtypes = {col: str(dtype) for col, dtype in feature_df.dtypes.items()}
missing_values = feature_df.isnull().sum().to_dict()
missing_pct = {col: (v / len(feature_df)) * 100 for col, v in missing_values.items()}
numerical_cols = feature_df.select_dtypes(include=[np.number]).columns.tolist()
categorical_cols = feature_df.select_dtypes(include=["object", "category"]).columns.tolist()
numerical_stats = {}
categorical_stats = {}
outliers_detected = {}
correlations = {}
for col in numerical_cols:
stats = feature_df[col].describe().to_dict()
stats["outliers"] = self._detect_outliers(feature_df[col], method="iqr")
stats["variance"] = (
float(feature_df[col].var()) if not feature_df[col].isnull().all() else 0.0
)
if self.learning_type == LearningType.CLUSTERING and stats.get("mean", 0) != 0:
stats["cv_coefficient"] = stats["std"] / stats["mean"]
numerical_stats[col] = {
k: float(v) if isinstance(v, (np.integer, np.floating)) else v
for k, v in stats.items()
}
outliers_detected[col] = stats["outliers"]
for col in categorical_cols:
categorical_stats[col] = {
"unique_values": int(feature_df[col].nunique()),
"most_frequent": (
str(feature_df[col].mode().iloc[0])
if not feature_df[col].mode().empty else None
),
"value_counts": {
str(k): int(v)
for k, v in feature_df[col].value_counts().head(10).items()
},
}
if len(numerical_cols) > 1:
corr_matrix = feature_df[numerical_cols].corr()
threshold = 0.9 if self.learning_type == LearningType.CLUSTERING else 0.7
for i in range(len(corr_matrix.columns)):
for j in range(i + 1, len(corr_matrix.columns)):
val = corr_matrix.iloc[i, j]
if abs(val) > threshold:
key = f"{corr_matrix.columns[i]}_vs_{corr_matrix.columns[j]}"
correlations[key] = float(val)
quality_metrics = self._calculate_quality_metrics(
feature_df, missing_pct, outliers_detected
)
return DataAnalysisReport(
shape=shape,
dtypes=dtypes,
missing_values=missing_values,
missing_percentage=missing_pct,
numerical_stats=numerical_stats,
categorical_stats=categorical_stats,
outliers_detected=outliers_detected,
correlations=correlations,
data_quality_score=quality_metrics["overall_score"],
target_column=target_column,
data_quality_metrics=quality_metrics,
ml_type=self.ml_type,
learning_type=self.learning_type,
)
# ------------------------------------------------------------------
# FIX #4: parameter renamed from `learning_type` to `method`
def _detect_outliers(self, series: pd.Series, method: str = "iqr") -> int:
"""Detect outliers using IQR. Parameter renamed to avoid shadowing self.learning_type."""
if not pd.api.types.is_numeric_dtype(series) or series.isnull().all():
return 0
Q1, Q3 = series.quantile(0.25), series.quantile(0.75)
IQR = Q3 - Q1
return int(((series < Q1 - 1.5 * IQR) | (series > Q3 + 1.5 * IQR)).sum())
# ------------------------------------------------------------------
def _calculate_quality_metrics(
self,
df: pd.DataFrame,
missing_pct: Dict[str, float],
outliers: Dict[str, int],
) -> Dict[str, Any]:
total_missing = sum(missing_pct.values()) / len(missing_pct) if missing_pct else 0
total_outliers = sum(outliers.values())
completeness = max(0, 100 - total_missing)
outlier_penalty = min(50, (total_outliers / len(df)) * 100)
overall = max(0, min(100, completeness - outlier_penalty))
return {
"overall_score": round(overall, 2),
"completeness_score": round(completeness, 2),
"total_missing_percentage": round(total_missing, 2),
"total_outliers": total_outliers,
"outlier_percentage": round((total_outliers / len(df)) * 100, 2),
}
# ------------------------------------------------------------------
def _get_llm_preprocessing_suggestion(
self,
df: pd.DataFrame,
report: DataAnalysisReport,
) -> Dict[str, Any]:
if self.learning_type in (LearningType.REGRESSION, LearningType.CLASSIFICATION):
system_prompt = SUPERVISED_COLUMN_SELECTION_SYSTEM_PROMPT
elif self.learning_type == LearningType.CLUSTERING:
system_prompt = CLUSTERING_COLUMN_SELECTION_SYSTEM_PROMPT
else:
raise ValueError(f"Unsupported learning_type: {self.learning_type}")
feature_columns = {
col: dtype
for col, dtype in report.dtypes.items()
if col != report.target_column
}
feature_df = (
df.drop(columns=[report.target_column], errors="ignore")
if report.target_column else df
)
input_data = {
"ml_type": self.ml_type.value,
"learning_type": self.learning_type.value,
"features": feature_columns,
"first_5_rows": feature_df.head(3).to_dict(orient="records"),
"column_names": list(feature_df.columns),
"shape": [feature_df.shape[0], feature_df.shape[1]],
"missing_values": report.missing_values,
"missing_percentage": report.missing_percentage,
"outliers_detected": report.outliers_detected,
"correlations": report.correlations,
"numerical_stats": report.numerical_stats,
"categorical_stats": report.categorical_stats,
"target_column": report.target_column,
"data_quality_metrics": report.data_quality_metrics,
}
logger.info(
f"Requesting preprocessing suggestions for "
f"{self.ml_type.value}/{self.learning_type.value}…"
)
result = chat_llm(system_prompt, json.dumps(input_data, indent=2))
if not result:
logger.warning("LLM preprocessing suggestion failed — using default config.")
return self._get_default_preprocessing_config(report)
# Safety: strip target column from feature lists
if report.target_column:
for section in ["columns_to_drop", "columns_to_keep"]:
if section in result and "column_list" in result[section]:
result[section]["column_list"] = [
col for col in result[section]["column_list"]
if col != report.target_column
]
return result
# ------------------------------------------------------------------
def _get_default_preprocessing_config(
self, report: Optional[DataAnalysisReport] = None
) -> Dict[str, Any]:
return {
"columns_to_drop": {"column_list": [], "reasons": {}},
"columns_to_keep": {
"column_list": list(report.dtypes.keys()) if report else [],
"details": {},
},
"feature_engineering_suggestions": [],
"pipeline_recommendation": {},
"summary": {
"original_features": len(report.dtypes) if report else 0,
"recommended_features": len(report.dtypes) if report else 0,
"features_dropped": 0,
"new_features_created": 0,
"expected_model_improvement": "Default config — LLM call failed",
"key_insights": [],
},
}
# ------------------------------------------------------------------
def get_preprocessing_report(
self,
report: DataAnalysisReport,
preprocessing_config: Dict[str, Any],
) -> str:
lines = [
"=" * 80,
f"DATA ANALYSIS REPORT — {self.ml_type.value} / {self.learning_type.value}",
"=" * 80,
f"\nDataset Shape: {report.shape[0]} rows × {report.shape[1]} columns",
f"ML Task Type: {self.ml_type.value}",
f"Method: {self.learning_type.value}",
f"Target Column: {report.target_column or 'None (Unsupervised)'}",
f"Quality Score: {report.data_quality_score}/100",
f"\n{'='*80}\nCOLUMNS TO DROP:\n{'-'*80}",
]
for col in preprocessing_config.get("columns_to_drop", {}).get("column_list", []):
reasons = preprocessing_config["columns_to_drop"]["reasons"].get(col, [])
lines.append(f" • {col}")
for r in reasons:
lines.append(f" - {r}")
lines += [f"\n{'='*80}\nCOLUMNS TO KEEP (top 5 by priority):\n{'-'*80}"]
keep_details = preprocessing_config.get("columns_to_keep", {}).get("details", {})
priority_map = {"high": 3, "medium": 2, "low": 1}
sorted_cols = sorted(
keep_details.items(),
key=lambda x: priority_map.get(x[1].get("priority", "low"), 0),
reverse=True,
)[:5]
for col, details in sorted_cols:
lines.append(
f" • {col} (Priority: {details.get('priority')}, "
f"Confidence: {details.get('confidence')})"
)
lines.append(f" Reason: {details.get('reason')}")
lines.append(
f" Preprocessing: "
f"{', '.join(details.get('recommended_preprocessing', []))}"
)
s = preprocessing_config.get("summary", {})
lines += [
f"\n{'='*80}\nSUMMARY:\n{'-'*80}",
f" Original Features: {s.get('original_features', 'N/A')}",
f" Recommended Features: {s.get('recommended_features', 'N/A')}",
f" Features Dropped: {s.get('features_dropped', 'N/A')}",
f" New Features Created: {s.get('new_features_created', 'N/A')}",
f"\n Expected Impact: {s.get('expected_model_improvement', 'N/A')}",
f"\n{'='*80}\n",
]
return "\n".join(lines)
# ==============================================================================
# SECTION 7: FEATURE ENGINEERING ENGINE
# ==============================================================================
class FeatureEngineeringEngine:
"""Safe feature engineering — no exec()."""
ALLOWED_OPERATIONS = {
'divide': lambda df, a, b: df[a] / df[b].replace(0, np.nan),
'multiply': lambda df, a, b: df[a] * df[b],
'add': lambda df, a, b: df[a] + df[b],
'subtract': lambda df, a, b: df[a] - df[b],
}
@staticmethod
def create_feature(df: pd.DataFrame, config: Dict) -> pd.Series:
operation = config.get('operation')
source_cols = config['source_columns']
if operation not in FeatureEngineeringEngine.ALLOWED_OPERATIONS:
raise ValueError(
f"Operation '{operation}' not allowed. "
f"Use: {list(FeatureEngineeringEngine.ALLOWED_OPERATIONS.keys())}"
)
if len(source_cols) != 2:
raise ValueError(f"Operations require exactly 2 columns, got {len(source_cols)}")
missing = [c for c in source_cols if c not in df.columns]
if missing:
raise ValueError(f"Missing columns: {missing}")
result = FeatureEngineeringEngine.ALLOWED_OPERATIONS[operation](
df, source_cols[0], source_cols[1]
)
return result.replace([np.inf, -np.inf], np.nan)
# ==============================================================================
# SECTION 8: TARGET PROCESSOR
# ==============================================================================
class TargetProcessor:
"""Handles all target variable preprocessing."""
def __init__(self, learning_type: LearningType, verbose: bool = True):
self.learning_type = learning_type
self.verbose = verbose
self.encoder = None
self.winsorizer = None
self.label_mapping = {}
self._is_fitted = False
# ------------------------------------------------------------------
def fit_transform(