Python中使用sklearn 的 Pipeline 管道机制


pipeline管道机制使用方法:

流水线的输入为一连串的数据挖掘步骤,其中最后一步必须是估计器(Estimator),可理解成分类器
前几步是转换器(Transformer)。输入的数据集经过转换器的处理后,输出的结果作为下一步的输入。

最后,用位于流水线最后一步的估计器对数据进行分类。

 

每一步都用元组( ‘名称’,步骤)来表示。现在来创建流水线。

pipe = Pipeline([('sc',StandardScaler()), ('pca',PCA(n_components=2)), ('clf',LogisticRegression(random_state=666)) #设置随机种子,使测试结果复现 ])
#coding=gbk #sklearn 中pipeline管道机制的使用 ''' 流水线的功能: 跟踪记录各步骤的操作(以方便地重现实验结果) 对各步骤进行一个封装 确保代码的复杂程度不至于超出掌控范围 ''' import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.preprocessing import LabelEncoder data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/' 'breast-cancer-wisconsin/wdbc.data', header=None) print(data.shape) x, y = data.values[:,2:],data.values[:,1] encoder = LabelEncoder() y= encoder.fit_transform(y) #将 标签 'm', 'b' 转换成1,0 x_train, x_test, y_train, y_test = train_test_split(x,y,test_size= 0.2,random_state= 666) #使用pipeline管道机制 from sklearn.preprocessing import StandardScaler #规范化,使各特征的均值为1,方差为0 from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline pipe = Pipeline([('sc',StandardScaler()), ('pca',PCA(n_components=2)), ('clf',LogisticRegression(random_state=666)) #设置随机种子,使测试结果复现 ]) pipe.fit(x_train, y_train) print('Test accuracy is %.3f' % pipe.score(x_test, y_test)) # Test accuracy is 0.921

当我们执行 pipe.fit(X_train, y_train)时,首先由StandardScaler在训练集上执行 fit和transform方法,transformed后的数据又被传递给Pipeline对象的下一步,也即PCA()。和StandardScaler一样,PCA也是执行fit和transform方法,最终将转换后的数据传递给 LosigsticRegression。

 


参考:inside_zhang 的blog

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM