在sklearn中通过Pipeline来定义和自动化运行某些标准流程。
1.数据准备和生成模型的Pipeline
Pipeline能够处理训练数据集和评估数据集之间的数据泄露问题,通常会在数据处理过程中对分离出的所有数据子集做同样的数据处理,如正态化处理。
import pandas as pd
from sklearn.model_selection import KFold,cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
names=['preg','plas','pres','skin','test','mass','pedi','age','class']
data=pd.read_csv("pima_data.csv",names=names)
array=data.values
X=array[:,:8]
Y=array[:,8]
#通过pipeline实现数据正态化和线性判别分析模型的训练
kfold=KFold(n_splits=10,random_state=7,shuffle=True)
steps=[]
steps.append(('Standardize',StandardScaler()))
steps.append(('lda',LinearDiscriminantAnalysis()))
model=Pipeline(steps)
results=cross_val_score(model,X,Y,cv=kfold)
2. 特征选择和生成模型的pipeline
特征选择也是一个容易受到数据泄露影响的过程。
kfold=KFold(n_splits=10,random_state=7,shuffle=True)
#生成FeatureUnion
features=[]
features.append(('pca',PCA()))
features.append(('select_best',SelectKBest(k=6)))
#生成pipeline
steps=[]
steps.append(('feature_union',FeatureUnion(features)))
steps.append(('logistic',LogisticRegression()))
model=Pipeline(steps)
results=cross_val_score(model,X,Y,cv=kfold)
print(results.mean())
reference:《机器学习python实践》魏贞原,2018.