sklearn之pipeline:pipeline函数/make_pipeline函数的简介及其区别联系、使用技巧、案例应用之详细攻略

sklearn之pipeline:pipeline函数/make_pipeline函数的简介及其区别联系、使用技巧、案例应用之详细攻略

目录

sklearn.pipeline函数简介

1、Why pipeline管道机制?

2、sklearn.pipeline函数使用及其参数解释

3、sklearn的make_pipeline函数的代码解释、使用方法

sklearn的make_pipeline函数的代码解释

4、make_pipeline(自动)和pipeline(手动)的区别和联系

pipeline的案例应用

1、基础用法

sklearn的make_pipeline函数的使用方法

使用Pipeline类来表示在使用MinMaxScaler缩放数据之后再训练一个SVM的工作流程

make_pipeline函数创建管道

2、基于SVM的基础案例

3、其它案例


sklearn.pipeline函数简介

          转换器Transformers 通常与分类器、回归器或其他估计器相结合,构成一个复合估计器。最常见的工具是pipeline。pipeline通常与特征结合使用,特征结合将变压器的输出连接到一个复合特征空间中。TransformedTargetRegressor处理目标的转换(即log-transform y),相反,pipeline只转换观察到的数据(X)。
          管道可用于将多个估计器链成一个估计器。这是很有用的,因为在处理数据时通常有固定的步骤序列,例如特征选择、归一化和分类。管道在这里有多种用途:

  • 方便和封装:你只需要调用拟合并对你的数据进行一次预测,就可以拟合整个估计值序列。
  • 联合参数选择:您可以一次对管道中所有估计器的参数进行网格搜索。
  • 安全:管道可以确保使用相同的样本来训练转换器和预测器,从而避免将测试数据中的统计信息泄漏到交叉验证中训练过的模型中。

          管道中的所有评估器,除了最后一个,都必须是转换器(即必须有一个转换方法)。最后的估计器可以是任何类型(转换器、分类器等)。


官方文档6.1. Pipelines and composite estimators — scikit-learn 1.2.2 documentation

1、Why pipeline管道机制?

          Pipeline,中文翻译为管道,也可以称为流水线。他要做的就是把一系列的类连成一条流水线,然后让数据在流水线上“跑起来”。采用pipeline,生成机器学习整个流程的流水线,可方便的减少代码量同时让机器学习的流程变得直观。使用sklearn.pipeline.Pipeline(steps, memory=None)将各个步骤串联起来,可以很方便地保存模型。

  • Pipeline管道机制便于在不同新数据集上进行重复使用。Pipeline管道机制保证安全性:通过确保使用相同的样本来训练转换器和预测器。Pipeline有助于避免在交叉验证中将测试数据的统计信息泄漏到经过训练的模型中。
  • Pipeline管道机制实现了对ML全部步骤的流式化封装和管理,即streaming workflows with pipelines。Pipeline非常方便和封装,只需调用一次fit,接着在数据上进行一次predict即可拟合整个估计器序列。直接调用fit和predict方法来对pipeline中的所有算法模型进行训练和预测。
    例如,首先对数据进行了PCA降维,然后使用LoR进行分类。此时,如果不使用pipeline,那么很有可能要分别保存两部分内容,一部分是PCA模型,一部分是LoR模型,这样的话,使用起来会很不方便。
  • Pipeline管道机制可以将许多算法模型串联起来,比如将特征提取、归一化、分类组织在一起形成一个典型的机器学习问题工作流。Pipeline管道机制可将多个估计器连接为一个整体。众所周知,机器学习的数据处理阶段,通常会有固定的步骤顺序,比如特征选择,特征三化和类别化等。
  • Pipeline管道机制实现联合参数选择:可以结合grid search对参数进行选择。可以一次对Pipeline中所有估计器的参数进行网格搜索(grid search)。

2、sklearn.pipeline函数使用及其参数解释

class Pipeline(_BaseComposition):

    """

    Pipeline of transforms with a final estimator.

    Sequentially apply a list of transforms and a final estimator.

    Intermediate steps of the pipeline must be 'transforms', that is, they must implement fit and transform methods.

    The final estimator only needs to implement fit.

    The transformers in the pipeline can be cached using ``memory`` argument.

The purpose of the pipeline is to assemble several steps that can be cross-validated together while setting different parameters.

    For this, it enables setting parameters of the various steps using their  names and the parameter name separated by a '__', as in the example below.

    A step's estimator may be replaced entirely by setting the parameter with its name to another estimator, or a transformer removed by setting  it to 'passthrough' or ``None``.

    Read more in the :ref:`User Guide <pipeline>`.

    .. versionadded:: 0.5

具有最终估计器的转换管道。

按顺序应用一组转换和一个最终的估计器。

管道的中间步骤必须是“transforms”,也就是说,它们必须实现fit和transform方法。

最终的评估器只需要实现fit。

可以使用“memory”参数缓存管道中的转换器。

管道的目的是将几个可以交叉验证的步骤组装在一起,同时设置不同的参数。

为此,它允许使用它们的名称和由“__”分隔的参数名称来设置各个步骤的参数,如下例所示。

可以通过将参数的名称设置为另一个估计器来完全替换步骤的估计器,或者通过将其设置为“passthrough”或“None”来删除转换器。

详见:ref: ' User Guide  '。</pipeline>

. .versionadded:: 0.5

    Parameters

    ----------

    steps : list. List of (name, transform) tuples (implementing fit/transform) that are chained, in the order in which they are chained, with the last object an estimator.

    memory : str or object with the joblib.Memory interface, default=None. Used to cache the fitted transformers of the pipeline. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of the transformers before fitting. Therefore, the transformer instance given to the pipeline cannot be inspected directly. Use the attribute ``named_steps`` or ``steps`` to inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming.

    verbose : bool, default=False. If True, the time elapsed while fitting each step will be printed as it is completed.

    Attributes

    ----------

    named_steps: :class:`~sklearn.utils.Bunch`

    Dictionary-like object, with the following attributes. Read-only attribute to access any step parameter by user given name. Keys are step names and values are steps parameters.

    

    See Also

    --------

    sklearn.pipeline.make_pipeline : Convenience function for simplified pipeline construction.

steps :列表。(名称、转换)元组(实现fit/转换)的列表,按照它们被链接的顺序,最后一个对象是评估器。

memory:str或物体与joblib。内存接口,默认=没有。用于缓存安装在管道中的变压器。默认情况下,不执行缓存。如果给定一个字符串,它就是到缓存目录的路径。启用缓存会在安装前触发变压器的克隆。因此,给管线的变压器实例不能直接检查。使用属性' ' named_steps ' ' '或' ' steps ' '检查管道中的评估器。当装配耗时时,缓存变压器是有利的。

verbose :bool,默认=False。如果为真,在完成每个步骤时所经过的时间将被打印出来。

属性

----------

named_steps::类:“~ sklearn.utils.Bunch”

类字典的对象,具有以下属性。只读属性,按用户名访问任何步骤参数。键是步骤名称,值是步骤参数。

另请参阅

--------

sklearn.pipeline。make_pipeline:简化管道构造的方便函数。

    Examples

    --------

    >>> from sklearn.svm import SVC

    >>> from sklearn.preprocessing import StandardScaler

    >>> from sklearn.datasets import make_classification

    >>> from sklearn.model_selection import train_test_split

    >>> from sklearn.pipeline import Pipeline

    >>> X, y = make_classification(random_state=0)

    >>> X_train, X_test, y_train, y_test = train_test_split(X, y,

    ...                                                     random_state=0)

    >>> pipe = Pipeline([('scaler', StandardScaler()), ('svc', SVC())])

    >>> # The pipeline can be used as any other estimator

    >>> # and avoids leaking the test set into the train set

    >>> pipe.fit(X_train, y_train)

    Pipeline(steps=[('scaler', StandardScaler()), ('svc', SVC())])

    >>> pipe.score(X_test, y_test)

    0.88

3、sklearn的make_pipeline函数的代码解释、使用方法

          为了简化构建变换和模型链的过程,Scikit-Learn提供了pipeline类,可以将多个处理步骤合并为单个Scikit-Learn估计器。pipeline类本身具有fit、predict和score方法,其行为与Scikit-Learn中的其他模型相同。

sklearn的make_pipeline函数的代码解释

def make_pipeline(*steps, **kwargs):
    """Construct a Pipeline from the given estimators.

    This is a shorthand for the Pipeline constructor; it does not require, and does not permit, naming the estimators. Instead, their names will be set  to the lowercase of their types automatically.

    Parameters
    ----------
    *steps : list of estimators,

    memory : None, str or object with the joblib.Memory interface, optional
        Used to cache the fitted transformers of the pipeline. By default, no caching is performed. If a string is given, it is the path to the caching directory. Enabling caching triggers a clone of  the transformers before fitting. Therefore, the transformer  instance given to the pipeline cannot be inspected directly. Use the attribute ``named_steps`` or ``steps`` to  inspect estimators within the pipeline. Caching the transformers is advantageous when fitting is time consuming.

根据给定的估算器构造一条管道。

这是管道构造函数的简写;它不需要,也不允许命名估算器。相反,它们的名称将自动设置为类型的小写。

参数

    ----------

*steps :评估表、

memory:无,str或带有joblib的对象。内存接口,可选

用于缓存安装在管道中的变压器。默认情况下,不执行缓存。如果给定一个字符串,它就是到缓存目录的路径。启用缓存会在安装前触发变压器的克隆。因此,给管线的变压器实例不能直接检查。使用属性' ' named_steps ' ' '或' ' steps ' '检查管道中的评估器。当装配耗时时,缓存变压器是有利的。

    Examples
    --------
    >>> from sklearn.naive_bayes import GaussianNB
    >>> from sklearn.preprocessing import StandardScaler
    >>> make_pipeline(StandardScaler(), GaussianNB(priors=None))
    ...     # doctest: +NORMALIZE_WHITESPACE
    Pipeline(memory=None,
             steps=[('standardscaler',
                     StandardScaler(copy=True, with_mean=True, with_std=True)),
                    ('gaussiannb', GaussianNB(priors=None))])

    Returns
    -------
    p : Pipeline
    """
    memory = kwargs.pop('memory', None)
    if kwargs:
        raise TypeError('Unknown keyword arguments: "{}"'
                        .format(list(kwargs.keys())[0]))
    return Pipeline(_name_estimators(steps), memory=memory)

4、make_pipeline(自动)和pipeline(手动)的区别和联系

make_pipeline 是一种更方便的方法,可以自动为每个步骤指定一个名称,而 Pipeline 则需要手动指定每个步骤的名称

make_pipeline 函数可以将多个转换器和估计器(比如 StandardScalerPCALogisticRegression 等)按照顺序连接起来,形成一个机器学习管道,在这个例子中,make_pipeline 函数自动为每个步骤分配名称(比如第一个步骤会被命名为 standardscaler,第二个步骤会被命名为 pca),并将它们按照顺序连接起来。

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression

pipe = make_pipeline(
    StandardScaler(),
    PCA(n_components=2),
    LogisticRegression()
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression

pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('pca', PCA(n_components=2)),
    ('classifier', LogisticRegression())
])

pipeline的案例应用

1、基础用法

sklearn的make_pipeline函数的使用方法

    Examples
    --------
    >>> from sklearn.naive_bayes import GaussianNB
    >>> from sklearn.preprocessing import StandardScaler
    >>> make_pipeline(StandardScaler(), GaussianNB(priors=None))
    ...     # doctest: +NORMALIZE_WHITESPACE
    Pipeline(memory=None,
             steps=[('standardscaler',
                     StandardScaler(copy=True, with_mean=True, with_std=True)),
                    ('gaussiannb', GaussianNB(priors=None))])

    Returns
    -------
    p : Pipeline

使用Pipeline类来表示在使用MinMaxScaler缩放数据之后再训练一个SVM的工作流程

from sklearn.pipeline import Pipeline
pipe = Pipeline([("scaler",MinMaxScaler()),("svm",SVC())])
pip.fit(X_train,y_train)
pip.score(X_test,y_test)

make_pipeline函数创建管道

用Pipeline类构建管道时语法有点麻烦,我们通常不需要为每一个步骤提供用户指定的名称,这种情况下,就可以用make_pipeline函数创建管道,它可以为我们创建管道并根据每个步骤所属的类为其自动命名。

from sklearn.pipeline import make_pipeline
pipe = make_pipeline(MinMaxScaler(),SVC())

参考文章
《Python机器学习基础教程》构建管道(make_pipeline)
Python sklearn.pipeline.make_pipeline() Examples

2、基于SVM的基础案例

        简单使用管道,连续运行单变量特征选择与方差分析,然后支持向量机的选择特征。利用子管道将拟合系数映射回原始特征空间。

from sklearn import svm
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report

print(__doc__)

# import some data to play with
X, y = make_classification(
    n_features=20, n_informative=3, n_redundant=0, n_classes=4,
    n_clusters_per_class=2)

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

# ANOVA SVM-C
# 1) anova filter, take 3 best ranked features
anova_filter = SelectKBest(f_regression, k=3)
# 2) svm
clf = svm.LinearSVC()

anova_svm = make_pipeline(anova_filter, clf)
anova_svm.fit(X_train, y_train)
y_pred = anova_svm.predict(X_test)
print(classification_report(y_test, y_pred))

coef = anova_svm[:-1].inverse_transform(anova_svm['linearsvc'].coef_)
print(coef)

3、其它案例

ML之LoR:利用pipeline对digits数据集(PCA可视化+GSCV网格搜索+pkl模型保存)采用LoR算法实现多分类
ML之DT:利用pipeline对titanic数据集(均值填充+类别字段转数值字段+分类矩阵报告)采用DictVectorizer、DT技术实现二分类案例
ML之LoR:利用pipeline对fetch_20newsgroups数据集(文本抽取TfidfVectorizer)采用SVC算法(GSCV)实现多分类

### 回答1: make_pipeline()函数是一个方便的函数,可以用来创建一个管道对象,该对象可以将多个步骤组合在一起,以便在机器学习模型中使用。该函数的参数是一系列的步骤,每个步骤都是一个机器学习算法或数据预处理操作。管道对象可以像普通的机器学习模型一样进行训练和预测,但是它可以自动地将数据传递给下一个步骤,从而简化了机器学习的流程。 ### 回答2: make_pipeline()函数Python sklearn(Scikit-learn)中一个非常实用的函数,它能够将多个算法模型串联成一个完整的管道(Pipeline)模型,用来处理数据集。同时,它还可以帮助我们自动进行模型选择和参数调优。 make_pipeline()函数的语法格式为: make_pipeline(*steps, **kwargs) 其中,*steps参数是一个可变参数,用来传递多个算法模型,**kwargs参数则用于传递Pipeline对象的其他参数。 下面我们来看看make_pipeline()函数的具体用法: 1. 导入所需要的库和数据集 首先,我们需要导入所需要的库和数据集。比如: from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target 2. 将多个算法模型进行组合 在上面的示例中,我们将标准化处理和逻辑回归模型组合成一个管道模型。代码如下: pipe_lr = make_pipeline(StandardScaler(), LogisticRegression()) 其中,StandardScaler()是将数据标准化的预处理操作,LogisticRegression()是选用的分类算法模型。 3. 拟合和预测 最后,我们可以通过拟合和预测对模型进行评估,比如: pipe_lr.fit(X_train, y_train) y_pred = pipe_lr.predict(X_test) 在这个例子中,我们首先将数据集(X, y)划分成训练集(X_train, y_train)和测试集(X_test, y_test)。然后,通过pipe_lr.fit()方法训练模型,并通过pipe_lr.predict()方法进行预测。 总的来说,make_pipeline()函数提供了一种便捷的方式来组合多个算法模型,并能够加快我们进行数据分析的速度。同时,它还能够自动帮我们进行参数调优,能够让我们更快速地找到最优的模型。 ### 回答3: make_pipeline()是一个简单的函数,它可以帮助我们快速地创建一个sklearn pipeline对象。它可以接受多个步骤作为输入,每个步骤都是一个sklearn估计器或转换器。它会在每个步骤之间自动连接转换器和估计器,生成一个完整的Pipeline对象。make_pipeline()的输入应该是转换器和估计器的列表。 make_pipeline()的作用可以用一个例子来解释。我们可以使用make_pipeline()来创建一个Pipeline对象,它接受一些数据并进行3个步骤的处理:标准化、PCA降维和逻辑回归模型拟合。 这个Pipeline的代码如下所示: ``` from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression pipe = make_pipeline( StandardScaler(), PCA(n_components=2), LogisticRegression(random_state=42) ) ``` 这个例子中,我们使用make_pipeline()创建了一个Pipeline对象,将StandardScaler标准化对象、PCA降维对象和逻辑回归模型对象连接在一起。这个Pipeline对象能够接受数据作为输入,经过标准化后,再进行PCA降维,最后将经过降维的数据拟合进逻辑回归模型中。 这里需要注意的是,Pipeline的最后一个对象必须是一个分类器或回归器,因为Pipeline的最后一个步骤需要拟合模型并进行预测。另外,make_pipeline()方法可以根据估计器和转换器传入的变量名进行命名,方便管道步骤的调用。 因此,make_pipeline()函数使得我们更方便地进行机器学习管道的构建和管理,使得我们可以更加高效地构建数据处理和建模的流程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个处女座的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值