Skip to content

估计器转换器

该文件是TPOT库的一部分。

当前版本的TPOT是由以下人员在Cedars-Sinai开发的: - Pedro Henrique Ribeiro (https://github.com/perib, https://www.linkedin.com/in/pedro-ribeiro/) - Anil Saini (anil.saini@cshs.org) - Jose Hernandez (jgh9094@gmail.com) - Jay Moran (jay.moran@cshs.org) - Nicholas Matsumoto (nicholas.matsumoto@cshs.org) - Hyunjun Choi (hyunjun.choi@cshs.org) - Miguel E. Hernandez (miguel.e.hernandez@cshs.org) - Jason Moore (moorejh28@gmail.com)

TPOT的原始版本主要由宾夕法尼亚大学的以下人员开发: - Randal S. Olson (rso@randalolson.com) - Weixuan Fu (weixuanf@upenn.edu) - Daniel Angell (dpa34@drexel.edu) - Jason Moore (moorejh28@gmail.com) - 以及许多慷慨的开源贡献者

TPOT 是免费软件:您可以根据自由软件基金会发布的 GNU 宽通用公共许可证的条款重新分发和/或修改它,许可证的版本可以是第 3 版,或者(根据您的选择)任何以后的版本。

TPOT 的发布是希望它能有用, 但没有任何保证;甚至没有对 适销性或特定用途适用性的暗示保证。更多详情请参阅 GNU 较宽松通用公共许可证。

您应该已经收到了一份GNU较宽松通用公共许可证的副本,随TPOT一起提供。如果没有,请参见http://www.gnu.org/licenses/

EstimatorTransformer

基类:BaseEstimator, TransformerMixin

Source code in tpot2/builtin_modules/estimatortransformer.py
class EstimatorTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, estimator, method='auto', passthrough=False, cross_val_predict_cv=None):
        """
        A class for using a sklearn estimator as a transformer. When calling fit_transform, this class returns the out put of cross_val_predict
        and trains the estimator on the full dataset. When calling transform, this class uses the estimator fit on the full dataset to transform the data.

        Parameters
        ----------
        estimator : sklear.base. BaseEstimator
            The estimator to use as a transformer.
        method : str, default='auto'
            The method to use for the transformation. If 'auto', will try to use predict_proba, decision_function, or predict in that order.
            - predict_proba: use the predict_proba method of the estimator.
            - decision_function: use the decision_function method of the estimator.
            - predict: use the predict method of the estimator.
        passthrough : bool, default=False
            Whether to pass the original input through.
        cross_val_predict_cv : int, default=0
            Number of folds to use for the cross_val_predict function for inner classifiers and regressors. Estimators will still be fit on the full dataset, but the following node will get the outputs from cross_val_predict.

            - 0-1 : When set to 0 or 1, the cross_val_predict function will not be used. The next layer will get the outputs from fitting and transforming the full dataset.
            - >=2 : When fitting pipelines with inner classifiers or regressors, they will still be fit on the full dataset.
                    However, the output to the next node will come from cross_val_predict with the specified number of folds.

        """
        self.estimator = estimator
        self.method = method
        self.passthrough = passthrough
        self.cross_val_predict_cv = cross_val_predict_cv

    def fit(self, X, y=None):
        self.estimator.fit(X, y)
        return self

    def transform(self, X, y=None):
        #Does not do cross val predict, just uses the estimator to transform the data. This is used for the actual transformation in practice, so the real transformation without fitting is needed
        if self.method == 'auto':
            if hasattr(self.estimator, 'predict_proba'):
                method = 'predict_proba'
            elif hasattr(self.estimator, 'decision_function'):
                method = 'decision_function'
            elif hasattr(self.estimator, 'predict'):
                method = 'predict'
            else:
                raise ValueError('Estimator has no valid method')
        else:
            method = self.method

        output = getattr(self.estimator, method)(X)
        output=np.array(output)

        if len(output.shape) == 1:
            output = output.reshape(-1,1)

        if self.passthrough:
            return np.hstack((output, X))
        else:
            return output



    def fit_transform(self, X, y=None):
        #Does use cross_val_predict if cross_val_predict_cv is greater than 0. this function is only used in training the model. 
        self.estimator.fit(X,y)

        if self.method == 'auto':
            if hasattr(self.estimator, 'predict_proba'):
                method = 'predict_proba'
            elif hasattr(self.estimator, 'decision_function'):
                method = 'decision_function'
            elif hasattr(self.estimator, 'predict'):
                method = 'predict'
            else:
                raise ValueError('Estimator has no valid method')
        else:
            method = self.method

        if self.cross_val_predict_cv is not None:
            output = cross_val_predict(self.estimator, X, y=y, cv=self.cross_val_predict_cv)
        else:
            output = getattr(self.estimator, method)(X)
            #reshape if needed

        if len(output.shape) == 1:
            output = output.reshape(-1,1)

        output=np.array(output)
        if self.passthrough:
            return np.hstack((output, X))
        else:
            return output

    def _estimator_has(attr):
        '''Check if we can delegate a method to the underlying estimator.
        First, we check the first fitted final estimator if available, otherwise we
        check the unfitted final estimator.
        '''
        return  lambda self: (self.estimator is not None and
            hasattr(self.estimator, attr)
        )

    @available_if(_estimator_has('predict'))
    def predict(self, X, **predict_params):
        check_is_fitted(self.estimator)
        #X = check_array(X)

        preds = self.estimator.predict(X,**predict_params)
        return preds

    @available_if(_estimator_has('predict_proba'))
    def predict_proba(self, X, **predict_params):
        check_is_fitted(self.estimator)
        #X = check_array(X)
        return self.estimator.predict_proba(X,**predict_params)

    @available_if(_estimator_has('decision_function'))
    def decision_function(self, X, **predict_params):
        check_is_fitted(self.estimator)
        #X = check_array(X)
        return self.estimator.decision_function(X,**predict_params)

    def __sklearn_is_fitted__(self):
        """
        Check fitted status and return a Boolean value.
        """
        return check_is_fitted(self.estimator)


    # @property
    # def _estimator_type(self):
    #     return self.estimator._estimator_type



    @property
    def classes_(self):
        """The classes labels. Only exist if the last step is a classifier."""
        return self.estimator._classes

classes_ property

类别标签。仅当最后一步是分类器时存在。

__init__(estimator, method='auto', passthrough=False, cross_val_predict_cv=None)

一个用于将sklearn估计器用作转换器的类。当调用fit_transform时,该类返回cross_val_predict的输出,并在完整数据集上训练估计器。当调用transform时,该类使用在完整数据集上拟合的估计器来转换数据。

参数:

名称 类型 描述 默认值
estimator BaseEstimator

用作转换器的估计器。

required
method str

用于转换的方法。如果为'auto',将尝试按顺序使用predict_proba、decision_function或predict。 - predict_proba: 使用估计器的predict_proba方法。 - decision_function: 使用估计器的decision_function方法。 - predict: 使用估计器的predict方法。

'auto'
passthrough bool

是否传递原始输入。

False
cross_val_predict_cv int

用于内部分类器和回归器的cross_val_predict函数的折叠次数。估计器仍将在完整数据集上进行拟合,但下一个节点将获得来自cross_val_predict的输出。

  • 0-1 : 当设置为0或1时,将不使用cross_val_predict函数。下一层将获得来自完整数据集的拟合和转换输出。
  • =2 : 当拟合具有内部分类器或回归器的管道时,它们仍将在完整数据集上进行拟合。 但是,下一个节点的输出将来自具有指定折叠次数的cross_val_predict。

0
Source code in tpot2/builtin_modules/estimatortransformer.py
def __init__(self, estimator, method='auto', passthrough=False, cross_val_predict_cv=None):
    """
    A class for using a sklearn estimator as a transformer. When calling fit_transform, this class returns the out put of cross_val_predict
    and trains the estimator on the full dataset. When calling transform, this class uses the estimator fit on the full dataset to transform the data.

    Parameters
    ----------
    estimator : sklear.base. BaseEstimator
        The estimator to use as a transformer.
    method : str, default='auto'
        The method to use for the transformation. If 'auto', will try to use predict_proba, decision_function, or predict in that order.
        - predict_proba: use the predict_proba method of the estimator.
        - decision_function: use the decision_function method of the estimator.
        - predict: use the predict method of the estimator.
    passthrough : bool, default=False
        Whether to pass the original input through.
    cross_val_predict_cv : int, default=0
        Number of folds to use for the cross_val_predict function for inner classifiers and regressors. Estimators will still be fit on the full dataset, but the following node will get the outputs from cross_val_predict.

        - 0-1 : When set to 0 or 1, the cross_val_predict function will not be used. The next layer will get the outputs from fitting and transforming the full dataset.
        - >=2 : When fitting pipelines with inner classifiers or regressors, they will still be fit on the full dataset.
                However, the output to the next node will come from cross_val_predict with the specified number of folds.

    """
    self.estimator = estimator
    self.method = method
    self.passthrough = passthrough
    self.cross_val_predict_cv = cross_val_predict_cv

__sklearn_is_fitted__()

检查拟合状态并返回一个布尔值。

Source code in tpot2/builtin_modules/estimatortransformer.py
def __sklearn_is_fitted__(self):
    """
    检查拟合状态并返回一个布尔值。
    """
    return check_is_fitted(self.estimator)