ds-agent-cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ds-agent.js +451 -0
- package/ds_agent/__init__.py +8 -0
- package/package.json +28 -0
- package/requirements.txt +126 -0
- package/setup.py +35 -0
- package/src/__init__.py +7 -0
- package/src/_compress_tool_result.py +118 -0
- package/src/api/__init__.py +4 -0
- package/src/api/app.py +1626 -0
- package/src/cache/__init__.py +5 -0
- package/src/cache/cache_manager.py +561 -0
- package/src/cli.py +2886 -0
- package/src/dynamic_prompts.py +281 -0
- package/src/orchestrator.py +4799 -0
- package/src/progress_manager.py +139 -0
- package/src/reasoning/__init__.py +332 -0
- package/src/reasoning/business_summary.py +431 -0
- package/src/reasoning/data_understanding.py +356 -0
- package/src/reasoning/model_explanation.py +383 -0
- package/src/reasoning/reasoning_trace.py +239 -0
- package/src/registry/__init__.py +3 -0
- package/src/registry/tools_registry.py +3 -0
- package/src/session_memory.py +448 -0
- package/src/session_store.py +370 -0
- package/src/storage/__init__.py +19 -0
- package/src/storage/artifact_store.py +620 -0
- package/src/storage/helpers.py +116 -0
- package/src/storage/huggingface_storage.py +694 -0
- package/src/storage/r2_storage.py +0 -0
- package/src/storage/user_files_service.py +288 -0
- package/src/tools/__init__.py +335 -0
- package/src/tools/advanced_analysis.py +823 -0
- package/src/tools/advanced_feature_engineering.py +708 -0
- package/src/tools/advanced_insights.py +578 -0
- package/src/tools/advanced_preprocessing.py +549 -0
- package/src/tools/advanced_training.py +906 -0
- package/src/tools/agent_tool_mapping.py +326 -0
- package/src/tools/auto_pipeline.py +420 -0
- package/src/tools/autogluon_training.py +1480 -0
- package/src/tools/business_intelligence.py +860 -0
- package/src/tools/cloud_data_sources.py +581 -0
- package/src/tools/code_interpreter.py +390 -0
- package/src/tools/computer_vision.py +614 -0
- package/src/tools/data_cleaning.py +614 -0
- package/src/tools/data_profiling.py +593 -0
- package/src/tools/data_type_conversion.py +268 -0
- package/src/tools/data_wrangling.py +433 -0
- package/src/tools/eda_reports.py +284 -0
- package/src/tools/enhanced_feature_engineering.py +241 -0
- package/src/tools/feature_engineering.py +302 -0
- package/src/tools/matplotlib_visualizations.py +1327 -0
- package/src/tools/model_training.py +520 -0
- package/src/tools/nlp_text_analytics.py +761 -0
- package/src/tools/plotly_visualizations.py +497 -0
- package/src/tools/production_mlops.py +852 -0
- package/src/tools/time_series.py +507 -0
- package/src/tools/tools_registry.py +2133 -0
- package/src/tools/visualization_engine.py +559 -0
- package/src/utils/__init__.py +42 -0
- package/src/utils/error_recovery.py +313 -0
- package/src/utils/parallel_executor.py +402 -0
- package/src/utils/polars_helpers.py +248 -0
- package/src/utils/schema_extraction.py +132 -0
- package/src/utils/semantic_layer.py +392 -0
- package/src/utils/token_budget.py +411 -0
- package/src/utils/validation.py +377 -0
- package/src/workflow_state.py +154 -0
|
@@ -0,0 +1,906 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Advanced Model Training Tools
|
|
3
|
+
Tools for hyperparameter tuning, ensemble methods, and cross-validation.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import polars as pl
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import numpy as np
|
|
9
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import sys
|
|
12
|
+
import os
|
|
13
|
+
import joblib
|
|
14
|
+
import json
|
|
15
|
+
import optuna
|
|
16
|
+
from optuna.pruners import MedianPruner
|
|
17
|
+
from optuna.samplers import TPESampler
|
|
18
|
+
import warnings
|
|
19
|
+
import tempfile
|
|
20
|
+
|
|
21
|
+
warnings.filterwarnings('ignore')
|
|
22
|
+
|
|
23
|
+
# Add parent directory to path for imports
|
|
24
|
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
25
|
+
|
|
26
|
+
# Import artifact store
|
|
27
|
+
try:
|
|
28
|
+
from storage.helpers import save_model_with_store
|
|
29
|
+
ARTIFACT_STORE_AVAILABLE = True
|
|
30
|
+
except ImportError:
|
|
31
|
+
ARTIFACT_STORE_AVAILABLE = False
|
|
32
|
+
print("⚠️ Artifact store not available, using local paths")
|
|
33
|
+
|
|
34
|
+
from sklearn.model_selection import train_test_split, KFold, StratifiedKFold, TimeSeriesSplit, cross_val_score
|
|
35
|
+
from sklearn.linear_model import LogisticRegression, Ridge, Lasso, ElasticNet
|
|
36
|
+
from sklearn.ensemble import (
|
|
37
|
+
RandomForestClassifier, RandomForestRegressor,
|
|
38
|
+
GradientBoostingClassifier, GradientBoostingRegressor,
|
|
39
|
+
VotingClassifier, VotingRegressor,
|
|
40
|
+
StackingClassifier, StackingRegressor
|
|
41
|
+
)
|
|
42
|
+
from xgboost import XGBClassifier, XGBRegressor
|
|
43
|
+
from sklearn.metrics import (
|
|
44
|
+
accuracy_score, precision_score, recall_score, f1_score, roc_auc_score,
|
|
45
|
+
mean_squared_error, mean_absolute_error, r2_score
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
from ds_agent.utils.polars_helpers import load_dataframe, get_numeric_columns, split_features_target
|
|
49
|
+
from ds_agent.utils.validation import (
|
|
50
|
+
validate_file_exists, validate_file_format, validate_dataframe,
|
|
51
|
+
validate_column_exists, validate_target_column
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def hyperparameter_tuning(
|
|
56
|
+
file_path: str,
|
|
57
|
+
target_col: str,
|
|
58
|
+
model_type: str = "random_forest",
|
|
59
|
+
task_type: str = "auto",
|
|
60
|
+
n_trials: int = 50,
|
|
61
|
+
cv_folds: int = 5,
|
|
62
|
+
optimization_metric: str = "auto",
|
|
63
|
+
test_size: float = 0.2,
|
|
64
|
+
random_state: int = 42,
|
|
65
|
+
output_path: Optional[str] = None
|
|
66
|
+
) -> Dict[str, Any]:
|
|
67
|
+
"""
|
|
68
|
+
Perform Bayesian hyperparameter optimization using Optuna.
|
|
69
|
+
|
|
70
|
+
⚠️ WARNING: This tool is VERY computationally expensive and can take 5-10 minutes!
|
|
71
|
+
For large datasets (>100K rows), n_trials is automatically reduced to prevent timeout.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
file_path: Path to prepared dataset
|
|
75
|
+
target_col: Target column name
|
|
76
|
+
model_type: Model to tune ('random_forest', 'xgboost', 'lightgbm', 'catboost', 'logistic', 'ridge')
|
|
77
|
+
task_type: 'classification', 'regression', or 'auto' (detect from target)
|
|
78
|
+
n_trials: Number of optimization trials (default 50, auto-reduced for large datasets)
|
|
79
|
+
cv_folds: Number of cross-validation folds
|
|
80
|
+
optimization_metric: Metric to optimize ('auto', 'accuracy', 'f1', 'roc_auc', 'rmse', 'r2')
|
|
81
|
+
test_size: Test set size for final evaluation
|
|
82
|
+
random_state: Random seed
|
|
83
|
+
output_path: Path to save best model
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
Dictionary with tuning results, best parameters, and performance
|
|
87
|
+
"""
|
|
88
|
+
# ⚠️ CRITICAL FIX: Convert integer params (Gemini/LLMs pass floats)
|
|
89
|
+
n_trials = int(n_trials)
|
|
90
|
+
cv_folds = int(cv_folds)
|
|
91
|
+
random_state = int(random_state)
|
|
92
|
+
|
|
93
|
+
# Validation
|
|
94
|
+
validate_file_exists(file_path)
|
|
95
|
+
validate_file_format(file_path)
|
|
96
|
+
|
|
97
|
+
# Load data
|
|
98
|
+
df = load_dataframe(file_path)
|
|
99
|
+
validate_dataframe(df)
|
|
100
|
+
validate_column_exists(df, target_col)
|
|
101
|
+
|
|
102
|
+
# ⚠️ CRITICAL: Auto-reduce trials for large datasets to prevent memory crashes
|
|
103
|
+
n_rows = len(df)
|
|
104
|
+
if n_rows > 100000 and n_trials > 20:
|
|
105
|
+
original_trials = n_trials
|
|
106
|
+
n_trials = 20
|
|
107
|
+
print(f" ⚠️ Large dataset ({n_rows:,} rows) - reducing trials from {original_trials} to {n_trials} to prevent timeout")
|
|
108
|
+
elif n_rows > 50000 and n_trials > 30:
|
|
109
|
+
original_trials = n_trials
|
|
110
|
+
n_trials = 30
|
|
111
|
+
print(f" ⚠️ Medium dataset ({n_rows:,} rows) - reducing trials from {original_trials} to {n_trials}")
|
|
112
|
+
|
|
113
|
+
# ⚠️ PERFORMANCE FIX: Sample large datasets for hyperparameter tuning
|
|
114
|
+
# Hyperparameters found on sample will be used to train final model on full dataset
|
|
115
|
+
MAX_TUNING_ROWS = 50000
|
|
116
|
+
sampled = False
|
|
117
|
+
if n_rows > MAX_TUNING_ROWS:
|
|
118
|
+
original_rows = n_rows
|
|
119
|
+
sample_frac = MAX_TUNING_ROWS / n_rows
|
|
120
|
+
df = df.sample(n=MAX_TUNING_ROWS, random_state=random_state)
|
|
121
|
+
sampled = True
|
|
122
|
+
print(f" 📊 Sampled {MAX_TUNING_ROWS:,} rows ({sample_frac:.1%}) from {original_rows:,} for faster tuning")
|
|
123
|
+
print(f" 💡 Hyperparameters found on sample will generalize well to full dataset")
|
|
124
|
+
print(f" ⏱️ Expected speedup: 3-5x faster tuning")
|
|
125
|
+
|
|
126
|
+
# ⚠️ Auto-reduce CV folds for very large datasets
|
|
127
|
+
original_cv_folds = cv_folds
|
|
128
|
+
if n_rows > 100000 and cv_folds > 3:
|
|
129
|
+
cv_folds = 3
|
|
130
|
+
print(f" ⏱️ Using {cv_folds}-fold CV (instead of {original_cv_folds}) for faster tuning on large dataset")
|
|
131
|
+
|
|
132
|
+
# ⚠️ SKIP DATETIME CONVERSION: Already handled by create_time_features() in workflow step 7
|
|
133
|
+
# The encoded.csv file should already have time features extracted
|
|
134
|
+
# If datetime columns still exist, they will be handled as regular features
|
|
135
|
+
|
|
136
|
+
# ⚠️ CRITICAL FIX: Convert Polars to Pandas if needed (for XGBoost compatibility)
|
|
137
|
+
if hasattr(df, 'to_pandas'):
|
|
138
|
+
print(f" 🔄 Converting Polars DataFrame to Pandas for XGBoost compatibility...")
|
|
139
|
+
df = df.to_pandas()
|
|
140
|
+
|
|
141
|
+
# ⚠️ CRITICAL: Drop any remaining datetime columns that weren't converted to features
|
|
142
|
+
# XGBoost cannot handle Timestamp objects in NumPy arrays
|
|
143
|
+
if isinstance(df, pd.DataFrame):
|
|
144
|
+
datetime_cols = df.select_dtypes(include=['datetime64', 'datetime64[ns]', 'datetime64[ns, UTC]']).columns.tolist()
|
|
145
|
+
if datetime_cols:
|
|
146
|
+
print(f" ⚠️ Dropping {len(datetime_cols)} datetime columns that cannot be used directly: {datetime_cols}")
|
|
147
|
+
print(f" 💡 Time features should have been extracted in workflow step 7 (create_time_features)")
|
|
148
|
+
df = df.drop(columns=datetime_cols)
|
|
149
|
+
|
|
150
|
+
# ⚠️ CRITICAL: Drop any remaining string/object columns (not encoded properly)
|
|
151
|
+
# XGBoost cannot handle string values like 'mb', 'ml', etc.
|
|
152
|
+
object_cols = df.select_dtypes(include=['object', 'string']).columns.tolist()
|
|
153
|
+
# Don't drop the target column if it's object type
|
|
154
|
+
object_cols = [col for col in object_cols if col != target_col]
|
|
155
|
+
if object_cols:
|
|
156
|
+
print(f" ⚠️ Dropping {len(object_cols)} string columns that weren't encoded: {object_cols}")
|
|
157
|
+
print(f" 💡 Categorical encoding should have been done in workflow step 8 (encode_categorical)")
|
|
158
|
+
print(f" 💡 These columns likely weren't in the encoded file or encoding failed")
|
|
159
|
+
df = df.drop(columns=object_cols)
|
|
160
|
+
|
|
161
|
+
# Prepare data - handle both Polars and Pandas
|
|
162
|
+
if target_col not in df.columns:
|
|
163
|
+
raise ValueError(f"Target column '{target_col}' not found in dataframe. Available columns: {list(df.columns)}")
|
|
164
|
+
|
|
165
|
+
# Split features and target (works for both Polars and Pandas)
|
|
166
|
+
if hasattr(df, 'drop'): # Both have drop method
|
|
167
|
+
X = df.drop(columns=[target_col]) if isinstance(df, pd.DataFrame) else df.drop(target_col)
|
|
168
|
+
y = df[target_col]
|
|
169
|
+
else:
|
|
170
|
+
X, y = split_features_target(df, target_col)
|
|
171
|
+
|
|
172
|
+
# Convert to numpy for sklearn compatibility
|
|
173
|
+
if hasattr(X, 'to_numpy'):
|
|
174
|
+
X = X.to_numpy()
|
|
175
|
+
y = y.to_numpy()
|
|
176
|
+
elif hasattr(X, 'values'):
|
|
177
|
+
X = X.values
|
|
178
|
+
y = y.values
|
|
179
|
+
|
|
180
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
181
|
+
X, y, test_size=test_size, random_state=random_state, stratify=y if task_type == "classification" else None
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# Detect task type
|
|
185
|
+
if task_type == "auto":
|
|
186
|
+
unique_values = len(np.unique(y))
|
|
187
|
+
task_type = "classification" if unique_values < 20 else "regression"
|
|
188
|
+
|
|
189
|
+
# Set default metric
|
|
190
|
+
if optimization_metric == "auto":
|
|
191
|
+
optimization_metric = "accuracy" if task_type == "classification" else "rmse"
|
|
192
|
+
|
|
193
|
+
# Define objective function for Optuna
|
|
194
|
+
def objective(trial):
|
|
195
|
+
# Suggest hyperparameters based on model type
|
|
196
|
+
if model_type == "random_forest":
|
|
197
|
+
params = {
|
|
198
|
+
'n_estimators': trial.suggest_int('n_estimators', 50, 500),
|
|
199
|
+
'max_depth': trial.suggest_int('max_depth', 3, 20),
|
|
200
|
+
'min_samples_split': trial.suggest_int('min_samples_split', 2, 20),
|
|
201
|
+
'min_samples_leaf': trial.suggest_int('min_samples_leaf', 1, 10),
|
|
202
|
+
'max_features': trial.suggest_categorical('max_features', ['sqrt', 'log2', None]),
|
|
203
|
+
'random_state': random_state
|
|
204
|
+
}
|
|
205
|
+
if task_type == "classification":
|
|
206
|
+
model = RandomForestClassifier(**params)
|
|
207
|
+
else:
|
|
208
|
+
model = RandomForestRegressor(**params)
|
|
209
|
+
|
|
210
|
+
elif model_type == "xgboost":
|
|
211
|
+
params = {
|
|
212
|
+
'n_estimators': trial.suggest_int('n_estimators', 50, 500),
|
|
213
|
+
'max_depth': trial.suggest_int('max_depth', 3, 10),
|
|
214
|
+
'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.3, log=True),
|
|
215
|
+
'subsample': trial.suggest_float('subsample', 0.5, 1.0),
|
|
216
|
+
'colsample_bytree': trial.suggest_float('colsample_bytree', 0.5, 1.0),
|
|
217
|
+
'gamma': trial.suggest_float('gamma', 0, 5),
|
|
218
|
+
'reg_alpha': trial.suggest_float('reg_alpha', 0, 2),
|
|
219
|
+
'reg_lambda': trial.suggest_float('reg_lambda', 0, 2),
|
|
220
|
+
'random_state': random_state
|
|
221
|
+
}
|
|
222
|
+
if task_type == "classification":
|
|
223
|
+
model = XGBClassifier(**params, use_label_encoder=False, eval_metric='logloss')
|
|
224
|
+
else:
|
|
225
|
+
model = XGBRegressor(**params)
|
|
226
|
+
|
|
227
|
+
elif model_type == "logistic":
|
|
228
|
+
params = {
|
|
229
|
+
'C': trial.suggest_float('C', 0.001, 100, log=True),
|
|
230
|
+
'penalty': trial.suggest_categorical('penalty', ['l1', 'l2', 'elasticnet']),
|
|
231
|
+
'solver': 'saga',
|
|
232
|
+
'max_iter': 1000,
|
|
233
|
+
'random_state': random_state
|
|
234
|
+
}
|
|
235
|
+
if params['penalty'] == 'elasticnet':
|
|
236
|
+
params['l1_ratio'] = trial.suggest_float('l1_ratio', 0, 1)
|
|
237
|
+
model = LogisticRegression(**params)
|
|
238
|
+
|
|
239
|
+
elif model_type == "ridge":
|
|
240
|
+
params = {
|
|
241
|
+
'alpha': trial.suggest_float('alpha', 0.001, 100, log=True),
|
|
242
|
+
'solver': trial.suggest_categorical('solver', ['auto', 'svd', 'cholesky', 'lsqr']),
|
|
243
|
+
'random_state': random_state
|
|
244
|
+
}
|
|
245
|
+
model = Ridge(**params)
|
|
246
|
+
|
|
247
|
+
elif model_type == "lightgbm":
|
|
248
|
+
from lightgbm import LGBMClassifier, LGBMRegressor
|
|
249
|
+
params = {
|
|
250
|
+
'n_estimators': trial.suggest_int('n_estimators', 50, 500),
|
|
251
|
+
'max_depth': trial.suggest_int('max_depth', 3, 12),
|
|
252
|
+
'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.3, log=True),
|
|
253
|
+
'subsample': trial.suggest_float('subsample', 0.5, 1.0),
|
|
254
|
+
'colsample_bytree': trial.suggest_float('colsample_bytree', 0.5, 1.0),
|
|
255
|
+
'reg_alpha': trial.suggest_float('reg_alpha', 1e-8, 10.0, log=True),
|
|
256
|
+
'reg_lambda': trial.suggest_float('reg_lambda', 1e-8, 10.0, log=True),
|
|
257
|
+
'num_leaves': trial.suggest_int('num_leaves', 15, 127),
|
|
258
|
+
'min_child_samples': trial.suggest_int('min_child_samples', 5, 100),
|
|
259
|
+
'random_state': random_state,
|
|
260
|
+
'verbosity': -1
|
|
261
|
+
}
|
|
262
|
+
if task_type == "classification":
|
|
263
|
+
model = LGBMClassifier(**params)
|
|
264
|
+
else:
|
|
265
|
+
model = LGBMRegressor(**params)
|
|
266
|
+
|
|
267
|
+
elif model_type == "catboost":
|
|
268
|
+
from catboost import CatBoostClassifier, CatBoostRegressor
|
|
269
|
+
params = {
|
|
270
|
+
'iterations': trial.suggest_int('iterations', 50, 500),
|
|
271
|
+
'depth': trial.suggest_int('depth', 3, 10),
|
|
272
|
+
'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.3, log=True),
|
|
273
|
+
'l2_leaf_reg': trial.suggest_float('l2_leaf_reg', 1e-8, 10.0, log=True),
|
|
274
|
+
'bagging_temperature': trial.suggest_float('bagging_temperature', 0, 10),
|
|
275
|
+
'random_strength': trial.suggest_float('random_strength', 0, 10),
|
|
276
|
+
'random_seed': random_state,
|
|
277
|
+
'verbose': 0
|
|
278
|
+
}
|
|
279
|
+
if task_type == "classification":
|
|
280
|
+
model = CatBoostClassifier(**params)
|
|
281
|
+
else:
|
|
282
|
+
model = CatBoostRegressor(**params)
|
|
283
|
+
else:
|
|
284
|
+
raise ValueError(f"Unsupported model_type: {model_type}. Use 'random_forest', 'xgboost', 'lightgbm', 'catboost', 'logistic', or 'ridge'.")
|
|
285
|
+
|
|
286
|
+
# Cross-validation
|
|
287
|
+
if task_type == "classification":
|
|
288
|
+
cv = StratifiedKFold(n_splits=cv_folds, shuffle=True, random_state=random_state)
|
|
289
|
+
else:
|
|
290
|
+
cv = KFold(n_splits=cv_folds, shuffle=True, random_state=random_state)
|
|
291
|
+
|
|
292
|
+
# Select scoring metric
|
|
293
|
+
if optimization_metric == "accuracy":
|
|
294
|
+
scoring = 'accuracy'
|
|
295
|
+
elif optimization_metric == "f1":
|
|
296
|
+
scoring = 'f1_weighted'
|
|
297
|
+
elif optimization_metric == "roc_auc":
|
|
298
|
+
scoring = 'roc_auc_ovr_weighted'
|
|
299
|
+
elif optimization_metric == "rmse":
|
|
300
|
+
scoring = 'neg_root_mean_squared_error'
|
|
301
|
+
elif optimization_metric == "r2":
|
|
302
|
+
scoring = 'r2'
|
|
303
|
+
else:
|
|
304
|
+
scoring = 'accuracy' if task_type == "classification" else 'neg_root_mean_squared_error'
|
|
305
|
+
|
|
306
|
+
# Cross-validation score
|
|
307
|
+
scores = cross_val_score(model, X_train, y_train, cv=cv, scoring=scoring, n_jobs=-1)
|
|
308
|
+
|
|
309
|
+
# Return mean score (Optuna maximizes by default)
|
|
310
|
+
return scores.mean()
|
|
311
|
+
|
|
312
|
+
# Run optimization
|
|
313
|
+
print(f"🔧 Starting hyperparameter tuning with {n_trials} trials...")
|
|
314
|
+
study = optuna.create_study(
|
|
315
|
+
direction='maximize',
|
|
316
|
+
sampler=TPESampler(seed=random_state),
|
|
317
|
+
pruner=MedianPruner(n_startup_trials=5, n_warmup_steps=10)
|
|
318
|
+
)
|
|
319
|
+
study.optimize(objective, n_trials=n_trials, show_progress_bar=True)
|
|
320
|
+
|
|
321
|
+
# Get best parameters
|
|
322
|
+
best_params = study.best_params
|
|
323
|
+
best_score = study.best_value
|
|
324
|
+
|
|
325
|
+
print(f"✅ Best {optimization_metric}: {best_score:.4f}")
|
|
326
|
+
print(f"📊 Best parameters: {best_params}")
|
|
327
|
+
|
|
328
|
+
# Train final model with best parameters
|
|
329
|
+
if model_type == "random_forest":
|
|
330
|
+
if task_type == "classification":
|
|
331
|
+
final_model = RandomForestClassifier(**best_params)
|
|
332
|
+
else:
|
|
333
|
+
final_model = RandomForestRegressor(**best_params)
|
|
334
|
+
elif model_type == "xgboost":
|
|
335
|
+
if task_type == "classification":
|
|
336
|
+
final_model = XGBClassifier(**best_params, use_label_encoder=False, eval_metric='logloss')
|
|
337
|
+
else:
|
|
338
|
+
final_model = XGBRegressor(**best_params)
|
|
339
|
+
elif model_type == "logistic":
|
|
340
|
+
final_model = LogisticRegression(**best_params)
|
|
341
|
+
elif model_type == "ridge":
|
|
342
|
+
final_model = Ridge(**best_params)
|
|
343
|
+
|
|
344
|
+
final_model.fit(X_train, y_train)
|
|
345
|
+
|
|
346
|
+
# Evaluate on test set
|
|
347
|
+
y_pred = final_model.predict(X_test)
|
|
348
|
+
|
|
349
|
+
if task_type == "classification":
|
|
350
|
+
test_metrics = {
|
|
351
|
+
'accuracy': float(accuracy_score(y_test, y_pred)),
|
|
352
|
+
'precision': float(precision_score(y_test, y_pred, average='weighted', zero_division=0)),
|
|
353
|
+
'recall': float(recall_score(y_test, y_pred, average='weighted', zero_division=0)),
|
|
354
|
+
'f1': float(f1_score(y_test, y_pred, average='weighted', zero_division=0))
|
|
355
|
+
}
|
|
356
|
+
if len(np.unique(y)) == 2:
|
|
357
|
+
y_pred_proba = final_model.predict_proba(X_test)[:, 1]
|
|
358
|
+
test_metrics['roc_auc'] = float(roc_auc_score(y_test, y_pred_proba))
|
|
359
|
+
else:
|
|
360
|
+
test_metrics = {
|
|
361
|
+
'rmse': float(np.sqrt(mean_squared_error(y_test, y_pred))),
|
|
362
|
+
'mae': float(mean_absolute_error(y_test, y_pred)),
|
|
363
|
+
'r2': float(r2_score(y_test, y_pred))
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
# Save model if output path provided
|
|
367
|
+
actual_model_path = None
|
|
368
|
+
if output_path:
|
|
369
|
+
if ARTIFACT_STORE_AVAILABLE:
|
|
370
|
+
# Save using artifact store (returns internal storage path)
|
|
371
|
+
actual_model_path = save_model_with_store(
|
|
372
|
+
model_data=final_model,
|
|
373
|
+
filename=os.path.basename(output_path),
|
|
374
|
+
metadata={
|
|
375
|
+
"model_type": model_type,
|
|
376
|
+
"task_type": task_type,
|
|
377
|
+
"best_params": best_params,
|
|
378
|
+
"cv_score": float(best_score),
|
|
379
|
+
"test_metrics": test_metrics
|
|
380
|
+
}
|
|
381
|
+
)
|
|
382
|
+
# Also save to user-requested path for LLM to find it
|
|
383
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
384
|
+
joblib.dump(final_model, output_path)
|
|
385
|
+
print(f"💾 Model saved to: {output_path} (artifact store: {actual_model_path})")
|
|
386
|
+
else:
|
|
387
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
388
|
+
joblib.dump(final_model, output_path)
|
|
389
|
+
actual_model_path = output_path
|
|
390
|
+
print(f"💾 Model saved to: {output_path}")
|
|
391
|
+
|
|
392
|
+
return {
|
|
393
|
+
'status': 'success',
|
|
394
|
+
'model_type': model_type,
|
|
395
|
+
'task_type': task_type,
|
|
396
|
+
'n_trials': n_trials,
|
|
397
|
+
'best_params': best_params,
|
|
398
|
+
'best_cv_score': float(best_score),
|
|
399
|
+
'optimization_metric': optimization_metric,
|
|
400
|
+
'test_metrics': test_metrics,
|
|
401
|
+
'trials_summary': {
|
|
402
|
+
'total_trials': len(study.trials),
|
|
403
|
+
'best_trial': study.best_trial.number,
|
|
404
|
+
'completed_trials': len([t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE])
|
|
405
|
+
},
|
|
406
|
+
'model_path': output_path if output_path else None
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def train_ensemble_models(
|
|
411
|
+
file_path: str,
|
|
412
|
+
target_col: str,
|
|
413
|
+
ensemble_type: str = "voting",
|
|
414
|
+
task_type: str = "auto",
|
|
415
|
+
test_size: float = 0.2,
|
|
416
|
+
random_state: int = 42,
|
|
417
|
+
output_path: Optional[str] = None
|
|
418
|
+
) -> Dict[str, Any]:
|
|
419
|
+
"""
|
|
420
|
+
Train ensemble models using stacking, blending, or voting.
|
|
421
|
+
|
|
422
|
+
Args:
|
|
423
|
+
file_path: Path to prepared dataset
|
|
424
|
+
target_col: Target column name
|
|
425
|
+
ensemble_type: 'voting', 'stacking', or 'blending'
|
|
426
|
+
task_type: 'classification', 'regression', or 'auto'
|
|
427
|
+
test_size: Test set size
|
|
428
|
+
random_state: Random seed
|
|
429
|
+
output_path: Path to save ensemble model
|
|
430
|
+
|
|
431
|
+
Returns:
|
|
432
|
+
Dictionary with ensemble performance and comparison
|
|
433
|
+
"""
|
|
434
|
+
# Validation
|
|
435
|
+
validate_file_exists(file_path)
|
|
436
|
+
validate_file_format(file_path)
|
|
437
|
+
|
|
438
|
+
# Load data
|
|
439
|
+
df = load_dataframe(file_path)
|
|
440
|
+
validate_dataframe(df)
|
|
441
|
+
validate_column_exists(df, target_col)
|
|
442
|
+
|
|
443
|
+
# ⚠️ SKIP DATETIME CONVERSION: Already handled by create_time_features() in workflow step 7
|
|
444
|
+
# The encoded.csv file should already have time features extracted
|
|
445
|
+
|
|
446
|
+
# ⚠️ CRITICAL FIX: Convert Polars to Pandas if needed (for XGBoost compatibility)
|
|
447
|
+
if hasattr(df, 'to_pandas'):
|
|
448
|
+
print(f" 🔄 Converting Polars DataFrame to Pandas for XGBoost compatibility...")
|
|
449
|
+
df = df.to_pandas()
|
|
450
|
+
|
|
451
|
+
# ⚠️ CRITICAL: Drop remaining datetime columns BEFORE NumPy conversion
|
|
452
|
+
# XGBoost cannot handle Timestamp objects (causes TypeError: float() argument must be a string or a real number, not 'Timestamp')
|
|
453
|
+
if isinstance(df, pd.DataFrame):
|
|
454
|
+
datetime_cols = df.select_dtypes(include=['datetime64', 'datetime64[ns]', 'datetime64[ns, UTC]']).columns.tolist()
|
|
455
|
+
if datetime_cols:
|
|
456
|
+
print(f" ⚠️ Dropping {len(datetime_cols)} datetime columns: {datetime_cols}")
|
|
457
|
+
print(f" 💡 Time features should have been extracted in workflow step 7 (create_time_features)")
|
|
458
|
+
df = df.drop(columns=datetime_cols)
|
|
459
|
+
|
|
460
|
+
# ⚠️ CRITICAL: Drop any remaining string/object columns (not encoded properly)
|
|
461
|
+
object_cols = df.select_dtypes(include=['object', 'string']).columns.tolist()
|
|
462
|
+
object_cols = [col for col in object_cols if col != target_col]
|
|
463
|
+
if object_cols:
|
|
464
|
+
print(f" ⚠️ Dropping {len(object_cols)} string columns that weren't encoded: {object_cols}")
|
|
465
|
+
print(f" 💡 Categorical encoding should have been done in workflow step 8")
|
|
466
|
+
df = df.drop(columns=object_cols)
|
|
467
|
+
|
|
468
|
+
# Prepare data - handle both Polars and Pandas
|
|
469
|
+
if target_col not in df.columns:
|
|
470
|
+
raise ValueError(f"Target column '{target_col}' not found in dataframe. Available columns: {list(df.columns)}")
|
|
471
|
+
|
|
472
|
+
# Split features and target (works for both Polars and Pandas)
|
|
473
|
+
if hasattr(df, 'drop'):
|
|
474
|
+
X = df.drop(columns=[target_col]) if isinstance(df, pd.DataFrame) else df.drop(target_col)
|
|
475
|
+
y = df[target_col]
|
|
476
|
+
else:
|
|
477
|
+
X, y = split_features_target(df, target_col)
|
|
478
|
+
|
|
479
|
+
# Convert to numpy for sklearn compatibility
|
|
480
|
+
if hasattr(X, 'to_numpy'):
|
|
481
|
+
X = X.to_numpy()
|
|
482
|
+
y = y.to_numpy()
|
|
483
|
+
elif hasattr(X, 'values'):
|
|
484
|
+
X = X.values
|
|
485
|
+
y = y.values
|
|
486
|
+
|
|
487
|
+
# Detect task type
|
|
488
|
+
if task_type == "auto":
|
|
489
|
+
unique_values = len(np.unique(y))
|
|
490
|
+
task_type = "classification" if unique_values < 20 else "regression"
|
|
491
|
+
|
|
492
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
493
|
+
X, y, test_size=test_size, random_state=random_state,
|
|
494
|
+
stratify=y if task_type == "classification" else None
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
# Define base models
|
|
498
|
+
if task_type == "classification":
|
|
499
|
+
base_models = [
|
|
500
|
+
('lr', LogisticRegression(max_iter=1000, random_state=random_state)),
|
|
501
|
+
('rf', RandomForestClassifier(n_estimators=100, random_state=random_state)),
|
|
502
|
+
('xgb', XGBClassifier(n_estimators=100, random_state=random_state, use_label_encoder=False, eval_metric='logloss'))
|
|
503
|
+
]
|
|
504
|
+
meta_model = LogisticRegression(max_iter=1000, random_state=random_state)
|
|
505
|
+
else:
|
|
506
|
+
base_models = [
|
|
507
|
+
('ridge', Ridge(random_state=random_state)),
|
|
508
|
+
('rf', RandomForestRegressor(n_estimators=100, random_state=random_state)),
|
|
509
|
+
('xgb', XGBRegressor(n_estimators=100, random_state=random_state))
|
|
510
|
+
]
|
|
511
|
+
meta_model = Ridge(random_state=random_state)
|
|
512
|
+
|
|
513
|
+
# Train individual models for comparison
|
|
514
|
+
individual_results = {}
|
|
515
|
+
for name, model in base_models:
|
|
516
|
+
model.fit(X_train, y_train)
|
|
517
|
+
y_pred = model.predict(X_test)
|
|
518
|
+
|
|
519
|
+
if task_type == "classification":
|
|
520
|
+
individual_results[name] = {
|
|
521
|
+
'accuracy': float(accuracy_score(y_test, y_pred)),
|
|
522
|
+
'f1': float(f1_score(y_test, y_pred, average='weighted', zero_division=0))
|
|
523
|
+
}
|
|
524
|
+
else:
|
|
525
|
+
individual_results[name] = {
|
|
526
|
+
'rmse': float(np.sqrt(mean_squared_error(y_test, y_pred))),
|
|
527
|
+
'r2': float(r2_score(y_test, y_pred))
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
# Create ensemble
|
|
531
|
+
print(f"🎯 Building {ensemble_type} ensemble...")
|
|
532
|
+
|
|
533
|
+
if ensemble_type == "voting":
|
|
534
|
+
if task_type == "classification":
|
|
535
|
+
ensemble = VotingClassifier(estimators=base_models, voting='soft')
|
|
536
|
+
else:
|
|
537
|
+
ensemble = VotingRegressor(estimators=base_models)
|
|
538
|
+
|
|
539
|
+
elif ensemble_type == "stacking":
|
|
540
|
+
if task_type == "classification":
|
|
541
|
+
ensemble = StackingClassifier(
|
|
542
|
+
estimators=base_models,
|
|
543
|
+
final_estimator=meta_model,
|
|
544
|
+
cv=5
|
|
545
|
+
)
|
|
546
|
+
else:
|
|
547
|
+
ensemble = StackingRegressor(
|
|
548
|
+
estimators=base_models,
|
|
549
|
+
final_estimator=meta_model,
|
|
550
|
+
cv=5
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
elif ensemble_type == "blending":
|
|
554
|
+
# Split training data for blending
|
|
555
|
+
X_base_train, X_blend_train, y_base_train, y_blend_train = train_test_split(
|
|
556
|
+
X_train, y_train, test_size=0.3, random_state=random_state,
|
|
557
|
+
stratify=y_train if task_type == "classification" else None
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
# Train base models on base training set
|
|
561
|
+
base_predictions_train = []
|
|
562
|
+
base_predictions_test = []
|
|
563
|
+
|
|
564
|
+
for name, model in base_models:
|
|
565
|
+
model.fit(X_base_train, y_base_train)
|
|
566
|
+
base_predictions_train.append(model.predict(X_blend_train))
|
|
567
|
+
base_predictions_test.append(model.predict(X_test))
|
|
568
|
+
|
|
569
|
+
# Stack predictions
|
|
570
|
+
X_blend = np.column_stack(base_predictions_train)
|
|
571
|
+
X_test_blend = np.column_stack(base_predictions_test)
|
|
572
|
+
|
|
573
|
+
# Train meta-model
|
|
574
|
+
meta_model.fit(X_blend, y_blend_train)
|
|
575
|
+
y_pred = meta_model.predict(X_test_blend)
|
|
576
|
+
|
|
577
|
+
# Calculate metrics
|
|
578
|
+
if task_type == "classification":
|
|
579
|
+
ensemble_metrics = {
|
|
580
|
+
'accuracy': float(accuracy_score(y_test, y_pred)),
|
|
581
|
+
'precision': float(precision_score(y_test, y_pred, average='weighted', zero_division=0)),
|
|
582
|
+
'recall': float(recall_score(y_test, y_pred, average='weighted', zero_division=0)),
|
|
583
|
+
'f1': float(f1_score(y_test, y_pred, average='weighted', zero_division=0))
|
|
584
|
+
}
|
|
585
|
+
else:
|
|
586
|
+
ensemble_metrics = {
|
|
587
|
+
'rmse': float(np.sqrt(mean_squared_error(y_test, y_pred))),
|
|
588
|
+
'mae': float(mean_absolute_error(y_test, y_pred)),
|
|
589
|
+
'r2': float(r2_score(y_test, y_pred))
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
# Save for blending
|
|
593
|
+
actual_model_path = None
|
|
594
|
+
if output_path:
|
|
595
|
+
if ARTIFACT_STORE_AVAILABLE:
|
|
596
|
+
# Save using artifact store (returns internal storage path)
|
|
597
|
+
actual_model_path = save_model_with_store(
|
|
598
|
+
model_data={
|
|
599
|
+
'base_models': dict(base_models),
|
|
600
|
+
'meta_model': meta_model,
|
|
601
|
+
'ensemble_type': 'blending'
|
|
602
|
+
},
|
|
603
|
+
filename=os.path.basename(output_path),
|
|
604
|
+
metadata={
|
|
605
|
+
"ensemble_type": "blending",
|
|
606
|
+
"task_type": task_type,
|
|
607
|
+
"ensemble_metrics": ensemble_metrics,
|
|
608
|
+
"num_base_models": len(base_models)
|
|
609
|
+
}
|
|
610
|
+
)
|
|
611
|
+
# Also save to user-requested path for LLM to find it
|
|
612
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
613
|
+
joblib.dump({
|
|
614
|
+
'base_models': dict(base_models),
|
|
615
|
+
'meta_model': meta_model,
|
|
616
|
+
'ensemble_type': 'blending'
|
|
617
|
+
}, output_path)
|
|
618
|
+
else:
|
|
619
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
620
|
+
joblib.dump({
|
|
621
|
+
'base_models': dict(base_models),
|
|
622
|
+
'meta_model': meta_model,
|
|
623
|
+
'ensemble_type': 'blending'
|
|
624
|
+
}, output_path)
|
|
625
|
+
actual_model_path = output_path
|
|
626
|
+
|
|
627
|
+
return {
|
|
628
|
+
'status': 'success',
|
|
629
|
+
'ensemble_type': ensemble_type,
|
|
630
|
+
'task_type': task_type,
|
|
631
|
+
'ensemble_metrics': ensemble_metrics,
|
|
632
|
+
'individual_models': individual_results,
|
|
633
|
+
'improvement': f"+{(ensemble_metrics.get('accuracy', ensemble_metrics.get('r2', 0)) - max([m.get('accuracy', m.get('r2', 0)) for m in individual_results.values()])) * 100:.2f}%",
|
|
634
|
+
'model_path': output_path if output_path else None
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
else:
|
|
638
|
+
raise ValueError(f"Unsupported ensemble_type: {ensemble_type}")
|
|
639
|
+
|
|
640
|
+
# Train ensemble (voting or stacking)
|
|
641
|
+
ensemble.fit(X_train, y_train)
|
|
642
|
+
y_pred = ensemble.predict(X_test)
|
|
643
|
+
|
|
644
|
+
# Calculate ensemble metrics
|
|
645
|
+
if task_type == "classification":
|
|
646
|
+
ensemble_metrics = {
|
|
647
|
+
'accuracy': float(accuracy_score(y_test, y_pred)),
|
|
648
|
+
'precision': float(precision_score(y_test, y_pred, average='weighted', zero_division=0)),
|
|
649
|
+
'recall': float(recall_score(y_test, y_pred, average='weighted', zero_division=0)),
|
|
650
|
+
'f1': float(f1_score(y_test, y_pred, average='weighted', zero_division=0))
|
|
651
|
+
}
|
|
652
|
+
best_individual_metric = max([m['accuracy'] for m in individual_results.values()])
|
|
653
|
+
improvement = ensemble_metrics['accuracy'] - best_individual_metric
|
|
654
|
+
else:
|
|
655
|
+
ensemble_metrics = {
|
|
656
|
+
'rmse': float(np.sqrt(mean_squared_error(y_test, y_pred))),
|
|
657
|
+
'mae': float(mean_absolute_error(y_test, y_pred)),
|
|
658
|
+
'r2': float(r2_score(y_test, y_pred))
|
|
659
|
+
}
|
|
660
|
+
best_individual_metric = max([m['r2'] for m in individual_results.values()])
|
|
661
|
+
improvement = ensemble_metrics['r2'] - best_individual_metric
|
|
662
|
+
|
|
663
|
+
# Save model
|
|
664
|
+
actual_model_path = None
|
|
665
|
+
if output_path:
|
|
666
|
+
if ARTIFACT_STORE_AVAILABLE:
|
|
667
|
+
# Save using artifact store (returns internal storage path)
|
|
668
|
+
actual_model_path = save_model_with_store(
|
|
669
|
+
model_data=ensemble,
|
|
670
|
+
filename=os.path.basename(output_path),
|
|
671
|
+
metadata={
|
|
672
|
+
"ensemble_type": ensemble_type,
|
|
673
|
+
"task_type": task_type,
|
|
674
|
+
"ensemble_metrics": ensemble_metrics,
|
|
675
|
+
"improvement_pct": float(improvement * 100)
|
|
676
|
+
}
|
|
677
|
+
)
|
|
678
|
+
# Also save to user-requested path for LLM to find it
|
|
679
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
680
|
+
joblib.dump(ensemble, output_path)
|
|
681
|
+
print(f"💾 Ensemble model saved to: {output_path} (artifact store: {actual_model_path})")
|
|
682
|
+
else:
|
|
683
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
684
|
+
joblib.dump(ensemble, output_path)
|
|
685
|
+
actual_model_path = output_path
|
|
686
|
+
print(f"💾 Ensemble model saved to: {output_path}")
|
|
687
|
+
|
|
688
|
+
return {
|
|
689
|
+
'status': 'success',
|
|
690
|
+
'ensemble_type': ensemble_type,
|
|
691
|
+
'task_type': task_type,
|
|
692
|
+
'ensemble_metrics': ensemble_metrics,
|
|
693
|
+
'individual_models': individual_results,
|
|
694
|
+
'improvement': f"+{improvement * 100:.2f}%",
|
|
695
|
+
'model_path': output_path if output_path else None
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def perform_cross_validation(
|
|
700
|
+
file_path: str,
|
|
701
|
+
target_col: str,
|
|
702
|
+
model_type: str = "random_forest",
|
|
703
|
+
task_type: str = "auto",
|
|
704
|
+
cv_strategy: str = "kfold",
|
|
705
|
+
n_splits: int = 5,
|
|
706
|
+
random_state: int = 42,
|
|
707
|
+
save_oof: bool = False,
|
|
708
|
+
output_path: Optional[str] = None
|
|
709
|
+
) -> Dict[str, Any]:
|
|
710
|
+
"""
|
|
711
|
+
Perform comprehensive cross-validation with out-of-fold predictions.
|
|
712
|
+
|
|
713
|
+
Args:
|
|
714
|
+
file_path: Path to prepared dataset
|
|
715
|
+
target_col: Target column name
|
|
716
|
+
model_type: 'random_forest', 'xgboost', 'logistic', 'ridge'
|
|
717
|
+
task_type: 'classification', 'regression', or 'auto'
|
|
718
|
+
cv_strategy: 'kfold', 'stratified', or 'timeseries'
|
|
719
|
+
n_splits: Number of CV folds
|
|
720
|
+
random_state: Random seed
|
|
721
|
+
save_oof: Whether to save out-of-fold predictions
|
|
722
|
+
output_path: Path to save OOF predictions
|
|
723
|
+
|
|
724
|
+
Returns:
|
|
725
|
+
Dictionary with CV scores, statistics, and OOF predictions
|
|
726
|
+
"""
|
|
727
|
+
# ⚠️ CRITICAL FIX: Convert n_splits and random_state to int (Gemini/LLMs pass floats)
|
|
728
|
+
n_splits = int(n_splits)
|
|
729
|
+
random_state = int(random_state)
|
|
730
|
+
|
|
731
|
+
# Validation
|
|
732
|
+
validate_file_exists(file_path)
|
|
733
|
+
validate_file_format(file_path)
|
|
734
|
+
|
|
735
|
+
# Load data
|
|
736
|
+
df = load_dataframe(file_path)
|
|
737
|
+
validate_dataframe(df)
|
|
738
|
+
validate_column_exists(df, target_col)
|
|
739
|
+
|
|
740
|
+
# ⚠️ SKIP DATETIME CONVERSION: Already handled by create_time_features() in workflow step 7
|
|
741
|
+
# The encoded.csv file should already have time features extracted
|
|
742
|
+
|
|
743
|
+
# ⚠️ CRITICAL FIX: Convert Polars to Pandas if needed (for XGBoost compatibility)
|
|
744
|
+
if hasattr(df, 'to_pandas'):
|
|
745
|
+
print(f" 🔄 Converting Polars DataFrame to Pandas for XGBoost compatibility...")
|
|
746
|
+
df = df.to_pandas()
|
|
747
|
+
|
|
748
|
+
# ⚠️ CRITICAL: Drop remaining datetime columns BEFORE NumPy conversion
|
|
749
|
+
# XGBoost cannot handle Timestamp objects (causes TypeError: float() argument must be a string or a real number, not 'Timestamp')
|
|
750
|
+
if isinstance(df, pd.DataFrame):
|
|
751
|
+
datetime_cols = df.select_dtypes(include=['datetime64', 'datetime64[ns]', 'datetime64[ns, UTC]']).columns.tolist()
|
|
752
|
+
if datetime_cols:
|
|
753
|
+
print(f" ⚠️ Dropping {len(datetime_cols)} datetime columns: {datetime_cols}")
|
|
754
|
+
print(f" 💡 Time features should have been extracted in workflow step 7 (create_time_features)")
|
|
755
|
+
df = df.drop(columns=datetime_cols)
|
|
756
|
+
|
|
757
|
+
# ⚠️ CRITICAL: Drop any remaining string/object columns (not encoded properly)
|
|
758
|
+
object_cols = df.select_dtypes(include=['object', 'string']).columns.tolist()
|
|
759
|
+
object_cols = [col for col in object_cols if col != target_col]
|
|
760
|
+
if object_cols:
|
|
761
|
+
print(f" ⚠️ Dropping {len(object_cols)} string columns that weren't encoded: {object_cols}")
|
|
762
|
+
print(f" 💡 Categorical encoding should have been done in workflow step 8")
|
|
763
|
+
df = df.drop(columns=object_cols)
|
|
764
|
+
|
|
765
|
+
# Prepare data - handle both Polars and Pandas
|
|
766
|
+
if target_col not in df.columns:
|
|
767
|
+
raise ValueError(f"Target column '{target_col}' not found in dataframe. Available columns: {list(df.columns)}")
|
|
768
|
+
|
|
769
|
+
# Split features and target (works for both Polars and Pandas)
|
|
770
|
+
if hasattr(df, 'drop'):
|
|
771
|
+
X = df.drop(columns=[target_col]) if isinstance(df, pd.DataFrame) else df.drop(target_col)
|
|
772
|
+
y = df[target_col]
|
|
773
|
+
else:
|
|
774
|
+
X, y = split_features_target(df, target_col)
|
|
775
|
+
|
|
776
|
+
# Convert to numpy for sklearn compatibility
|
|
777
|
+
if hasattr(X, 'to_numpy'):
|
|
778
|
+
X = X.to_numpy()
|
|
779
|
+
y = y.to_numpy()
|
|
780
|
+
elif hasattr(X, 'values'):
|
|
781
|
+
X = X.values
|
|
782
|
+
y = y.values
|
|
783
|
+
|
|
784
|
+
# Detect task type # Detect task type
|
|
785
|
+
if task_type == "auto":
|
|
786
|
+
unique_values = len(np.unique(y))
|
|
787
|
+
task_type = "classification" if unique_values < 20 else "regression"
|
|
788
|
+
|
|
789
|
+
# Create model
|
|
790
|
+
if model_type == "random_forest":
|
|
791
|
+
if task_type == "classification":
|
|
792
|
+
model = RandomForestClassifier(n_estimators=100, random_state=random_state)
|
|
793
|
+
else:
|
|
794
|
+
model = RandomForestRegressor(n_estimators=100, random_state=random_state)
|
|
795
|
+
elif model_type == "xgboost":
|
|
796
|
+
if task_type == "classification":
|
|
797
|
+
model = XGBClassifier(n_estimators=100, random_state=random_state, use_label_encoder=False, eval_metric='logloss')
|
|
798
|
+
else:
|
|
799
|
+
model = XGBRegressor(n_estimators=100, random_state=random_state)
|
|
800
|
+
elif model_type == "logistic":
|
|
801
|
+
model = LogisticRegression(max_iter=1000, random_state=random_state)
|
|
802
|
+
elif model_type == "ridge":
|
|
803
|
+
model = Ridge(random_state=random_state)
|
|
804
|
+
else:
|
|
805
|
+
raise ValueError(f"Unsupported model_type: {model_type}")
|
|
806
|
+
|
|
807
|
+
# Create CV splitter
|
|
808
|
+
# ⚠️ CRITICAL FIX: Auto-use StratifiedKFold for classification to avoid single-class folds
|
|
809
|
+
if cv_strategy == "timeseries":
|
|
810
|
+
cv = TimeSeriesSplit(n_splits=n_splits)
|
|
811
|
+
elif task_type == "classification":
|
|
812
|
+
# Always use stratified for classification (unless timeseries)
|
|
813
|
+
cv = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=random_state)
|
|
814
|
+
if cv_strategy != "stratified":
|
|
815
|
+
print(f" 💡 Auto-switching to StratifiedKFold for classification (prevents single-class folds)")
|
|
816
|
+
else:
|
|
817
|
+
# Regression: use regular KFold
|
|
818
|
+
cv = KFold(n_splits=n_splits, shuffle=True, random_state=random_state)
|
|
819
|
+
|
|
820
|
+
print(f"🔄 Performing {n_splits}-fold cross-validation ({cv_strategy})...")
|
|
821
|
+
|
|
822
|
+
# Perform cross-validation with detailed tracking
|
|
823
|
+
fold_scores = []
|
|
824
|
+
oof_predictions = np.zeros(len(y))
|
|
825
|
+
oof_indices = []
|
|
826
|
+
|
|
827
|
+
for fold_idx, (train_idx, val_idx) in enumerate(cv.split(X, y if cv_strategy == "stratified" else None)):
|
|
828
|
+
X_train_fold, X_val_fold = X[train_idx], X[val_idx]
|
|
829
|
+
y_train_fold, y_val_fold = y[train_idx], y[val_idx]
|
|
830
|
+
|
|
831
|
+
# Train model
|
|
832
|
+
model.fit(X_train_fold, y_train_fold)
|
|
833
|
+
|
|
834
|
+
# Predict on validation fold
|
|
835
|
+
y_pred_fold = model.predict(X_val_fold)
|
|
836
|
+
|
|
837
|
+
# Store OOF predictions
|
|
838
|
+
oof_predictions[val_idx] = y_pred_fold
|
|
839
|
+
oof_indices.extend(val_idx.tolist())
|
|
840
|
+
|
|
841
|
+
# Calculate fold metrics
|
|
842
|
+
if task_type == "classification":
|
|
843
|
+
fold_score = {
|
|
844
|
+
'fold': fold_idx + 1,
|
|
845
|
+
'accuracy': float(accuracy_score(y_val_fold, y_pred_fold)),
|
|
846
|
+
'f1': float(f1_score(y_val_fold, y_pred_fold, average='weighted', zero_division=0)),
|
|
847
|
+
'samples': len(val_idx)
|
|
848
|
+
}
|
|
849
|
+
else:
|
|
850
|
+
fold_score = {
|
|
851
|
+
'fold': fold_idx + 1,
|
|
852
|
+
'rmse': float(np.sqrt(mean_squared_error(y_val_fold, y_pred_fold))),
|
|
853
|
+
'r2': float(r2_score(y_val_fold, y_pred_fold)),
|
|
854
|
+
'samples': len(val_idx)
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
fold_scores.append(fold_score)
|
|
858
|
+
print(f" Fold {fold_idx + 1}: {fold_score}")
|
|
859
|
+
|
|
860
|
+
# Calculate overall OOF metrics
|
|
861
|
+
if task_type == "classification":
|
|
862
|
+
oof_metrics = {
|
|
863
|
+
'accuracy': float(accuracy_score(y, oof_predictions)),
|
|
864
|
+
'precision': float(precision_score(y, oof_predictions, average='weighted', zero_division=0)),
|
|
865
|
+
'recall': float(recall_score(y, oof_predictions, average='weighted', zero_division=0)),
|
|
866
|
+
'f1': float(f1_score(y, oof_predictions, average='weighted', zero_division=0))
|
|
867
|
+
}
|
|
868
|
+
mean_fold_metric = np.mean([f['accuracy'] for f in fold_scores])
|
|
869
|
+
std_fold_metric = np.std([f['accuracy'] for f in fold_scores])
|
|
870
|
+
metric_name = "accuracy"
|
|
871
|
+
else:
|
|
872
|
+
oof_metrics = {
|
|
873
|
+
'rmse': float(np.sqrt(mean_squared_error(y, oof_predictions))),
|
|
874
|
+
'mae': float(mean_absolute_error(y, oof_predictions)),
|
|
875
|
+
'r2': float(r2_score(y, oof_predictions))
|
|
876
|
+
}
|
|
877
|
+
mean_fold_metric = np.mean([f['rmse'] for f in fold_scores])
|
|
878
|
+
std_fold_metric = np.std([f['rmse'] for f in fold_scores])
|
|
879
|
+
metric_name = "rmse"
|
|
880
|
+
|
|
881
|
+
print(f"\n✅ Overall OOF {metric_name}: {oof_metrics.get(metric_name):.4f} (±{std_fold_metric:.4f})")
|
|
882
|
+
|
|
883
|
+
# Save OOF predictions if requested
|
|
884
|
+
if save_oof and output_path:
|
|
885
|
+
oof_df = pl.DataFrame({
|
|
886
|
+
'index': list(range(len(y))),
|
|
887
|
+
'true_values': y,
|
|
888
|
+
'oof_predictions': oof_predictions
|
|
889
|
+
})
|
|
890
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
891
|
+
oof_df.write_csv(output_path)
|
|
892
|
+
print(f"💾 OOF predictions saved to: {output_path}")
|
|
893
|
+
|
|
894
|
+
return {
|
|
895
|
+
'status': 'success',
|
|
896
|
+
'model_type': model_type,
|
|
897
|
+
'task_type': task_type,
|
|
898
|
+
'cv_strategy': cv_strategy,
|
|
899
|
+
'n_splits': n_splits,
|
|
900
|
+
'fold_scores': fold_scores,
|
|
901
|
+
'oof_metrics': oof_metrics,
|
|
902
|
+
'mean_cv_score': float(mean_fold_metric),
|
|
903
|
+
'std_cv_score': float(std_fold_metric),
|
|
904
|
+
'confidence_interval_95': f"[{mean_fold_metric - 1.96 * std_fold_metric:.4f}, {mean_fold_metric + 1.96 * std_fold_metric:.4f}]",
|
|
905
|
+
'oof_path': output_path if save_oof and output_path else None
|
|
906
|
+
}
|