sklearn.pipeline.Pileline

1. sklearn中的Pipeline机制

管道机制在机器学习算法中的应用:参数集在新数据集(比如测试集)上的重复使用。

管道机制实现流式化封装和管理。

2. 加载数据集并拆分

import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelEncoder

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/'
                 'breast-cancer-wisconsin/wdbc.data', header=None)
X, y = df.values[:, 2:], df.values[:, 1]  # y为标签

encoder = LabelEncoder()
y = encoder.fit_transform(y)
encoder.transform(['M', 'B'])
array([1, 0], dtype=int64)
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=.2,  
                                                    random_state=0)
print(y_train)
[0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0
 0 0 0 0 1 0 1 0 1 1 0 0 1 0 1 1 1 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 1 0 0 0 0
 1 0 0 1 1 0 0 1 1 0 0 1 0 0 1 1 1 0 0 0 1 0 0 0 0 0 1 0 1 0 1 0 1 0 1 0 0
 0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 1 0 1 0 1 0 1 0 0 1
 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 1 0 1 1 0 1 1 0
 0 1 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 0 0 1
 1 1 1 0 1 0 1 1 0 0 0 0 0 1 0 0 1 0 0 1 1 0 0 0 1 1 0 0 1 0 0 0 1 0 1 0 1
 1 1 1 0 0 0 0 1 1 0 0 0 0 0 1 0 0 1 0 0 1 1 1 1 0 0 1 0 0 0 1 1 0 0 0 0 0
 1 1 1 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 1 0 1 1 0 0 0 0 0 1 1 1 0 0 1
 1 0 0 1 0 1 1 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 1 0 1 1 1 0 1 0 1 0 1
 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 1 1 0 1 0 0 1
 1 1 1 0 1 1 1 0 1 0 1 0 0 1 1 0 1 0 0 0 0 1 0 0 1 0 0 0 1 1 0 0 0 1 0 0 1
 0 0 0 0 0 1 1 1 0 0 0]

3. 构造算流程

Pipeline是一个复合评估器,将多个具有上下逻辑环节的过程连接起来形成一个符合对象。

Pipeline只有一个参数“steps”,该参数是一个由名称和模型对象组成的元组列表

在这个列表中,不同元组之间是有明确的先后关系,并且最后一个元组一定是一个评估算法

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

pipe_lr = Pipeline([('sc', StandardScaler()),       #标准定标器
                    ('pca', PCA(n_components=2)),   
                    ('clf', LogisticRegression(random_state=1))
                    ])
pipe_lr.fit(X_train, y_train)
print('Test accuracy: %.3f' % pipe_lr.score(X_test, y_test))
Test accuracy: 0.921

4. Pipeline执行流程

上述代码,StandardScaler和PCA transformer是中间过度过程,LogisticRegression作为最终的评估器(estimator)。

当执行pipe_lr.fit(X_train, y_train)时,

首先由StandardScaler在训练集上执行fit和transform方法,

transformed后的数据又被传递给Pipeline对象的下一步,即PCA()

和StandardScaler一样,PCA也执行fit和transform方法,

最后将转换后的数据传递给LosigsticRegression。

来自:https://blog.csdn.net/wsp_1138886114/article/details/81179911

原文地址:https://www.cnblogs.com/keye/p/13365596.html