class OptunaOptimizer: """Optimizer class using Optuna for hyperparameter optimization.…
- User
class OptunaOptimizer: """Optimizer class using Optuna for hyperparameter optimization.
This class encapsulates the functionality for optimizing hyperparameters of a machine learning model using the Optuna framework. It supports optimization of parameters for model initialization, fitting, and prediction. Attributes: config (HPOptimizerConfig): Configuration for the optimizer. model (BasePredictorModel): The model to be optimized. scoring (Optional[Union[str, Callable[..., float]]]): The scoring metric to use. If a string, it should be one of the metrics in sklearn.metrics. If a callable, it should take two arguments (estimator, X) and return a float. If None, the default scorer for the estimator will be used. cv (Optional[Union[int, BaseCrossValidator, Iterable]]): Cross-validation strategy to use. If an integer, it should be the number of folds. If a BaseCrossValidator, it will be used directly. If an iterable, it will be passed to sklearn.model_selection.cross_val_score. If None, no cross-validation will be performed. n_trials (Optional[int]): The number of trials to run. If None, there is no limit on the number of trials. timeout (Optional[float]): The timeout in seconds for each trial. If None, there is no timeout. direction (OptunaStudyDirection): The direction of the optimization. See optuna.study.StudyDirection for more. sampler (Optional[BaseSampler]): The sampler to use. If None, the default sampler will be used (TPESampler). init_params (Optional[Sequence[OptunaParams]]): Init parameters to optimize during the initialization of the model. fit_params (Optional[Sequence[OptunaParams]]): Fit parameters to optimize during the fit method of the model. predict_params (Optional[Sequence[OptunaParams]]): Predict parameters to optimize during the predict method of the model. study (optuna.study.Study): Optuna study object. best_score (Optional[float]): Best score obtained during optimization. best_config (Optional[ModelConfig]): Best configuration obtained. """ _CONFIG = HPOptimizerConfig def __init__( self, config: Union[HPOptimizerConfig, Dict[str, Any]], model: BasePredictorModel, cv: BaseCrossValidator, ) -> None: """Initialize the OptunaOptimizer with configuration and model. Args: config (HPOptimizerConfig): Configuration for the optimizer. model (BasePredictorModel): The model to be optimized. cv (Optional[Union[int, BaseCrossValidator]]): Cross-validation strategy to use. """ if isinstance(config, dict): config = HPOptimizerConfig.model_validate(config) self.config = config self.model = model self.scoring = config.scoring self.cv = cv self.n_trials = config.n_trials self.timeout = config.timeout self.direction = config.direction self.sampler = config.sampler self.init_params = config.init_params self.fit_params = config.fit_params self.predict_params = config.predict_params self.study = optuna.create_study( study_name=config.name, sampler=self.sampler, direction=self.direction, ) self.best_score: Optional[float] = None self.best_config: Optional[ModelConfig] = None @mlflow_tracking(run_name=lambda trial, *_: str(trial.number), log_trial=True) def _objective( self, trial: Trial, X: MatrixType, y: VectorType, ) -> tuple[float, Trial]: """Objective function for Optuna optimization. This function sets the current model configuration based on the trial parameters and evaluates the model using cross-validation. Args: trial (Trial): Optuna trial object. X (MatrixType): Feature matrix. y (VectorType): Target vector. Returns: float: Mean cross-validated score. """ self._set_current_model_config(trial) model = self.model.clone(self._current_model_config) score = cross_val_score( estimator=model, X=X, y=y, scoring=self.scoring, cv=self.cv, ) trial.set_user_attr("config", self._current_model_config) mean_score = score.mean() return mean_score, trial def _set_current_model_config(self, trial: Trial) -> None: """Set the current model configuration based on trial parameters. This method updates the model configuration with parameters suggested by the Optuna trial. Args: trial (Trial): Optuna trial object. """ self._current_model_config = copy.deepcopy(self.model.config) self._current_model_config.init_params = self._get_model_params( constant_params=self._current_model_config.init_params, optimized_params=self.init_params, trial=trial, ) self._current_model_config.fit_params = self._get_model_params( constant_params=self._current_model_config.fit_params, optimized_params=self.fit_params, trial=trial, ) self._current_model_config.predict_params = self._get_model_params( constant_params=self._current_model_config.predict_params, optimized_params=self.predict_params, trial=trial, ) def _get_model_params( self, constant_params: Optional[MutableMapping[str, Any]], optimized_params: Optional[Sequence[OptunaBaseParam]], trial: Trial, ) -> Optional[MutableMapping[str, Any]]: """Get model parameters by combining constant and optimized parameters. This method merges constant parameters with parameters suggested by Optuna. Args: constant_params (Optional[MutableMapping[str, Any]]): Constant parameters for the model. optimized_params (Optional[Sequence[OptunaParam]]): Parameters to optimize. trial (Trial): Optuna trial object. Returns: Optional[MutableMapping[str, Any]]: Merged parameters. """ if optimized_params is None: return constant_params params = {} for param in optimized_params: params[param.name] = self._suggest_param(param, trial) new_params = {} if constant_params is not None: new_params = {**constant_params} new_params.update(params) return new_params @staticmethod def _suggest_param( param: OptunaBaseParam, trial: Trial, ) -> Union[None, float, str, int, bool]: return param.suggest(trial) @mlflow_tracking(run_name="optuna_study", log_outer=True) def fit(self, X: MatrixType, y: VectorType) -> None: """Run the optimization process. This method executes the optimization process using Optuna and stores the best configuration and score. Args: X (MatrixType): Feature matrix. y (VectorType): Target vector. """ self.study.optimize( func=lambda trial: self._objective(trial, X, y)[0], n_trials=self.n_trials, timeout=self.timeout, ) self.best_score = self.study.best_value self.best_config = self.study.best_trial.user_attrs["config"] self.trials_dataframe = self.study.trials_dataframe() Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.