如何在 XGBRegressor 的 MultiOutputRegressor 上使用验证集?

问题描述

我正在使用以下 MultIoUtputRegressor:

from xgboost import XGBRegressor
from sklearn.multIoUtput import MultIoUtputRegressor

#Define the estimator
estimator = XGBRegressor(
    objective = 'reg:squarederror'
    )

# Define the model
my_model = MultIoUtputRegressor(estimator = estimator,n_jobs = -1).fit(X_train,y_train)

我想使用验证集来评估我的 XGBRegressor 的性能,但是我相信 MultIoUtputRegressor 不支持eval_set 传递给 fit 函数

在这种情况下我如何使用验证集?是否有任何变通方法可以调整 XGBRegressor 以获得多个输出

解决方法

您可以尝试像这样编辑 fit 对象的 MultiOutputRegressor 方法:

from sklearn.utils.validation import _check_fit_params
from sklearn.base import is_classifier
from sklearn.utils.fixes import delayed
from joblib import Parallel
from sklearn.multioutput import _fit_estimator

class MyMultiOutputRegressor(MultiOutputRegressor):
    
    def fit(self,X,y,sample_weight=None,**fit_params):
        """ Fit the model to data.
        Fit a separate model for each output variable.
        Parameters
        ----------
        X : {array-like,sparse matrix} of shape (n_samples,n_features)
            Data.
        y : {array-like,n_outputs)
            Multi-output targets. An indicator matrix turns on multilabel
            estimation.
        sample_weight : array-like of shape (n_samples,),default=None
            Sample weights. If None,then samples are equally weighted.
            Only supported if the underlying regressor supports sample
            weights.
        **fit_params : dict of string -> object
            Parameters passed to the ``estimator.fit`` method of each step.
            .. versionadded:: 0.23
        Returns
        -------
        self : object
        """

        if not hasattr(self.estimator,"fit"):
            raise ValueError("The base estimator should implement"
                             " a fit method")

        X,y = self._validate_data(X,force_all_finite=False,multi_output=True,accept_sparse=True)

        if is_classifier(self):
            check_classification_targets(y)

        if y.ndim == 1:
            raise ValueError("y must have at least two dimensions for "
                             "multi-output regression but has only one.")

        if (sample_weight is not None and
                not has_fit_parameter(self.estimator,'sample_weight')):
            raise ValueError("Underlying estimator does not support"
                             " sample weights.")

        fit_params_validated = _check_fit_params(X,fit_params)
        [(X_test,Y_test)] = fit_params_validated.pop('eval_set')
        self.estimators_ = Parallel(n_jobs=self.n_jobs)(
            delayed(_fit_estimator)(
                self.estimator,y[:,i],sample_weight,**fit_params_validated,eval_set=[(X_test,Y_test[:,i])])
            for i in range(y.shape[1]))
        return self

然后将 eval_set 传递给 fit 方法:

fit_params = dict(
        eval_set=[(X_test,Y_test)],early_stopping_rounds=10
        )
model.fit(X_train,Y_train,**fit_params)