sklearn之pipeline:pipeline函数/make_pipeline函数的简介及其区别联系、使用技巧、案例应用之详细攻略
目录
3、sklearn的make_pipeline函数的代码解释、使用方法
4、make_pipeline(自动)和pipeline(手动)的区别和联系
使用Pipeline类来表示在使用MinMaxScaler缩放数据之后再训练一个SVM的工作流程
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): 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 memory : None, str or object with the joblib.Memory interface, optional | 根据给定的估算器构造一条管道。 这是管道构造函数的简写;它不需要,也不允许命名估算器。相反,它们的名称将自动设置为类型的小写。 参数 ---------- *steps :评估表、 memory:无,str或带有joblib的对象。内存接口,可选 用于缓存安装在管道中的变压器。默认情况下,不执行缓存。如果给定一个字符串,它就是到缓存目录的路径。启用缓存会在安装前触发变压器的克隆。因此,给管线的变压器实例不能直接检查。使用属性' ' named_steps ' ' '或' ' steps ' '检查管道中的评估器。当装配耗时时,缓存变压器是有利的。 |
Examples Returns |
4、make_pipeline(自动)和pipeline(手动)的区别和联系
make_pipeline 是一种更方便的方法,可以自动为每个步骤指定一个名称,而 Pipeline 则需要手动指定每个步骤的名称。
make_pipeline
函数可以将多个转换器和估计器(比如 StandardScaler
、PCA
、LogisticRegression
等)按照顺序连接起来,形成一个机器学习管道,在这个例子中,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)实现多分类