File size: 14,683 Bytes
714cf46 | 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 | import numpy as np
import pandas as pd
from sklearn.model_selection import RandomizedSearchCV
from typing import Dict, Any, Tuple, Optional
try:
from metrics import (
get_regression_scorer, get_classification_scorer,
classification_scorer, regression_scorer,
compute_single_label_classification_metrics,
compute_regression_metrics,
)
from utils import print_message
from seed_utils import get_global_seed
except ImportError:
from ..metrics import (
get_regression_scorer, get_classification_scorer,
classification_scorer, regression_scorer,
compute_single_label_classification_metrics,
compute_regression_metrics,
)
from ..utils import print_message
from ..seed_utils import get_global_seed
from transformers import EvalPrediction
from .lazy_predict import (
LazyRegressor,
LazyClassifier,
CLASSIFIER_DICT,
REGRESSOR_DICT,
ALL_MODEL_DICT
)
from .scikit_hypers import HYPERPARAMETER_DISTRIBUTIONS
class ScikitArguments:
"""
Combined arguments class for scikit-learn model training and tuning.
"""
def __init__(
self,
# Tuning arguments
n_iter: int = 100,
cv: int = 3,
random_state: Optional[int] = None,
# Specific model arguments (optional)
model_name: Optional[str] = None,
scikit_model_name: Optional[str] = None, # CLI arg name
scikit_model_args: Optional[str] = None, # CLI arg - JSON string
model_args: Optional[Dict[str, Any]] = None,
production_model: bool = False,
**kwargs,
):
import json
# Tuning arguments
self.n_iter = n_iter
self.cv = cv
self.random_state = random_state or get_global_seed()
# Specific model arguments - scikit_model_name takes precedence (CLI arg)
self.model_name = scikit_model_name or model_name
# Parse scikit_model_args JSON string if provided (CLI), otherwise use model_args dict
if scikit_model_args is not None:
try:
self.model_args = json.loads(scikit_model_args)
print_message(f"Using pre-specified hyperparameters (skipping tuning): {self.model_args}")
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse --scikit_model_args JSON: {e}")
else:
self.model_args = model_args if model_args is not None else {}
self.production_model = production_model
class ModelResults:
def __init__(
self,
initial_scores: Optional[pd.DataFrame],
best_model_name: str,
best_params: Optional[Dict[str, Any]],
final_scores: Dict[str, float],
best_model: Any
):
self.initial_scores = initial_scores
self.best_model_name = best_model_name
self.best_params = best_params
self.final_scores = final_scores
self.best_model = best_model
def __str__(self) -> str:
return (
f"Best Model: {self.best_model_name}\n"
f"Best Parameters: {self.best_params}\n"
f"Final Scores: {self.final_scores}"
)
class ScikitProbe:
"""
A class for finding and tuning the best scikit-learn models for a given dataset.
"""
def __init__(self, args: ScikitArguments):
self.args = args
self.n_jobs = 1
def _tune_hyperparameters(
self,
model_class: Any,
model_name: str,
X_train: np.ndarray,
y_train: np.ndarray,
custom_scorer: Any,
) -> Tuple[Any, Dict[str, Any]]:
"""
Perform hyperparameter tuning using RandomizedSearchCV.
"""
param_distributions = HYPERPARAMETER_DISTRIBUTIONS.get(model_name, {})
if not param_distributions:
print_message(f"No hyperparameter distributions defined for {model_name}, using defaults")
return model_class(), {}
print_message(f"Running RandomizedSearchCV with {self.args.n_iter} iterations, {self.args.cv}-fold CV...")
print_message(f"Hyperparameter search space: {list(param_distributions.keys())}")
random_search = RandomizedSearchCV(
model_class(),
param_distributions=param_distributions,
n_iter=self.args.n_iter,
scoring=custom_scorer,
cv=self.args.cv,
random_state=self.args.random_state,
n_jobs=self.n_jobs,
verbose=2 # Show progress for each fit
)
random_search.fit(X_train, y_train)
print_message(f"Best CV score: {random_search.best_score_:.4f}")
return random_search.best_estimator_, random_search.best_params_
def find_best_regressor(
self,
X_train: np.ndarray,
y_train: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
) -> ModelResults:
"""
Find the best regression model through lazy prediction and hyperparameter tuning.
Args:
X_train: Training features
y_train: Training targets
X_test: Test features
y_test: Test targets
Returns:
ModelResults object containing all results and the best model
"""
# Initial lazy prediction
print_message(f"Initial lazy prediction started")
regressor = LazyRegressor(
verbose=0,
ignore_warnings=False,
custom_metric=regression_scorer()
)
initial_scores = regressor.fit(X_train, X_test, y_train, y_test)
if isinstance(initial_scores, Tuple):
initial_scores = initial_scores[0]
# Get best model name and class
best_model_name = initial_scores.index[0]
# Models are now stored directly (not as Pipeline) after optimization
best_model_class = regressor.models[best_model_name].__class__
print_message(f"Best model name: {best_model_name}")
print_message(f"Best model class: {best_model_class}")
print_message(f"Initial scores: \n{initial_scores}")
print_message(f"Tuning hyperparameters")
# Tune hyperparameters
scorer = get_regression_scorer()
best_model, best_params = self._tune_hyperparameters(
best_model_class,
best_model_name,
X_train,
y_train,
scorer,
)
# Get final scores with tuned model
best_model.fit(X_train, y_train)
final_scores = self._calculate_metrics(best_model, X_test, y_test, best_model_name)
print_message(f"Final scores: {final_scores}")
print_message(f"Best params: \n{best_params}")
return ModelResults(
initial_scores=initial_scores,
best_model_name=best_model_name,
best_params=best_params,
final_scores=final_scores,
best_model=best_model
)
def find_best_classifier(
self,
X_train: np.ndarray,
y_train: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
) -> ModelResults:
"""
Find the best classification model through lazy prediction and hyperparameter tuning.
Args:
X_train: Training features
y_train: Training targets
X_test: Test features
y_test: Test targets
Returns:
ModelResults object containing all results and the best model
"""
# Initial lazy prediction
print_message(f"Initial lazy prediction started")
classifier = LazyClassifier(
verbose=0,
ignore_warnings=False,
custom_metric=classification_scorer()
)
initial_scores = classifier.fit(X_train, X_test, y_train, y_test)
if isinstance(initial_scores, Tuple):
initial_scores = initial_scores[0]
# Get best model name and class
best_model_name = initial_scores.index[0]
# Models are now stored directly (not as Pipeline) after optimization
best_model_class = classifier.models[best_model_name].__class__
print_message(f"Best model name: {best_model_name}")
print_message(f"Best model class: {best_model_class}")
print_message(f"Initial scores: \n{initial_scores}")
print_message(f"Tuning hyperparameters")
# Tune hyperparameters
scorer = get_classification_scorer()
best_model, best_params = self._tune_hyperparameters(
best_model_class,
best_model_name,
X_train,
y_train,
scorer,
)
# Get final scores with tuned model
best_model.fit(X_train, y_train)
final_scores = self._calculate_metrics(best_model, X_test, y_test, best_model_name)
print_message(f"Final scores: {final_scores}")
print_message(f"Best params: \n{best_params}")
return ModelResults(
initial_scores=initial_scores,
best_model_name=best_model_name,
best_params=best_params,
final_scores=final_scores,
best_model=best_model
)
def _calculate_metrics(
self,
model: Any,
X: np.ndarray,
y: np.ndarray,
model_name: str,
) -> Dict[str, float]:
"""
Delegate to the shared metric functions in metrics.py via EvalPrediction,
keeping a single source of truth for metric calculation across the codebase.
"""
if model_name in CLASSIFIER_DICT:
if hasattr(model, 'predict_proba'):
predictions = model.predict_proba(X)
else:
# Fall back to one-hot hard predictions for models without predict_proba
y_pred = model.predict(X)
n_classes = len(np.unique(y))
predictions = np.eye(n_classes)[y_pred.astype(int)]
p = EvalPrediction(predictions=predictions, label_ids=y)
return compute_single_label_classification_metrics(p)
elif model_name in REGRESSOR_DICT:
y_pred = model.predict(X)
p = EvalPrediction(predictions=y_pred, label_ids=y)
return compute_regression_metrics(p)
return {}
def run_specific_model(
self,
X_train: np.ndarray,
y_train: np.ndarray,
X_valid: np.ndarray,
y_valid: np.ndarray,
X_test: np.ndarray,
y_test: np.ndarray,
model_results: Optional[ModelResults] = None,
) -> ModelResults:
"""
Run a specific model with given arguments or based on a previous ModelResults.
Args:
X_train: Training features
y_train: Training targets
X_valid: Validation features
y_valid: Validation targets
X_test: Test features
y_test: Test targets
model_results: Optional ModelResults from find_best_classifier or find_best_regressor
If provided, will use the best model type and parameters from it
Returns:
ModelResults object containing results and the model
"""
print_message("Running specific model")
if self.args.production_model:
print_message(f"Running in production mode, train and validation are combined")
X_train = np.concatenate([X_train, X_valid])
y_train = np.concatenate([y_train, y_valid])
# If model_results is provided, use its best model type and parameters
if model_results is not None:
model_name = model_results.best_model_name
model_params = model_results.best_params if model_results.best_params is not None else {}
# Get the model class
model_class = ALL_MODEL_DICT[model_name]
# Create and train the model with the best parameters
cls = model_class(**model_params)
print_message(f"Training model {cls}")
cls.fit(X_train, y_train)
print_message(f"Model trained")
final_scores = self._calculate_metrics(cls, X_test, y_test, model_name)
print_message(f"Final scores: {final_scores}")
return ModelResults(
initial_scores=None,
best_model_name=model_name,
best_params=model_params,
final_scores=final_scores,
best_model=cls
)
# Original functionality when no model_results is provided
elif self.args.model_name is not None:
model_name = self.args.model_name
if model_name in CLASSIFIER_DICT:
scorer = get_classification_scorer()
elif model_name in REGRESSOR_DICT:
scorer = get_regression_scorer()
else:
raise ValueError(f"Model {model_name} not supported")
model_class = ALL_MODEL_DICT[model_name]
# Skip tuning if model_args is already provided
if self.args.model_args:
print_message(f"Skipping hyperparameter tuning - using provided args: {self.args.model_args}")
best_model = model_class(**self.args.model_args)
best_params = self.args.model_args
else:
# Run hyperparameter tuning
print_message(f"Tuning hyperparameters for {model_name}")
best_model, best_params = self._tune_hyperparameters(
model_class,
model_name,
X_train,
y_train,
scorer
)
print_message(f"Best parameters: {best_params}")
# Train final model with best parameters
print_message(f"Training final model with best parameters")
best_model.fit(X_train, y_train)
final_scores = self._calculate_metrics(best_model, X_test, y_test, model_name)
print_message(f"Final scores: {final_scores}")
return ModelResults(
initial_scores=None,
best_model_name=model_name,
best_params=best_params,
final_scores=final_scores,
best_model=best_model
)
else:
raise ValueError("Either model_name must be specified in args or model_results must be provided")
|