Pipeline模块介绍
Pipelines ,直译是“管道“, 类似于流水线的意思,可以将数据预处理和建模流程封装起来。 在数据处理过程中,很多步骤都是重复或者类似的,比如特征选择处理、归一化、分类等等,pipeline就可以实现以下几点好处:
简化代码:数据预处理过程是很繁杂凌乱的,pipeline 可以直接将步骤封装成完整的工作流,避免了代码重复。更少出Bug:流程规范化了,就能在避免在建模过程中漏掉某个步骤。更易于生产/复制:将建好的模型应用到实际数据,或者大规模部署到不同的数据集时,过程会非常繁琐,我们不需要在处理很多的问题,但Pipline可以帮助我们省略这些重复的过程,直接调用fit和predict来对所有算法模型进行训练和预测。简化模型验证过程:比如将pipeline 和交叉验证结合有助于防止来自测试数据的统计数据泄露到交叉验证的训练模型中。或者与网格搜索(Grid Search)结合,快速遍历所有参数的结果。
Pipeline是使用 (key,value) 对的列表构建的,其中key是步骤名称的字符串,而value是一个估计器对象。
代码示例
数据准备
import pandas as pd
from sklearn.model_selection import train_test_split
# 数据读取
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
# 切分目标值和训练数据
y = data.Price
X = data.drop(['Price'], axis=1)
# 训练集验证集切分
X_train_full, X_valid_full, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2,random_state=0)
# 分类型变量
categorical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].nunique() < 10 and
X_train_full[cname].dtype == "object"]
# 数值型变量
numerical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].dtype in ['int64', 'float64']]
# Keep selected columns only
my_cols = categorical_cols + numerical_cols
X_train = X_train_full[my_cols].copy()
X_valid = X_valid_full[my_cols].copy()
建立Pipelines
步骤一:确定预处理步骤
处理数值型变量的缺失值处理分类型变量的缺失值并且使用独热编码
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
# SimpleImputer处理缺失值
# strategy:空值填充的策略:mean、median、most_frequent、constant。
#mean表示该列的缺失值由该列的均值填充。median为中位数,most_frequent为众数。
#constant表示将空值填充为自定义的值,但这个自定义的值要通过fill_value来定义。
numerical_transformer = SimpleImputer(strategy='constant')
#这里使用pipeline将两个处理过程打包。
# OneHotEncoder:将每个分类特征转换成0-1数值型编码
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# 将数值和分类数据的预处理打包起来
#ColumnTransformer()可以选择地进行数据转换。
#使用时必须指定一个转换器列表。每个转换器是一个三元素元组,用于定义转换器的名称,要应用的转换以及要应用于其的列索引。
# 例如:(名称,对象,列)
preprocessor = ColumnTransformer(
transformers=[
('num', numerical_transformer, numerical_cols),
('cat', categorical_transformer, categorical_cols)
])
步骤二:定义模型
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_estimators=100, random_state=0)
步骤三:创建管道Pipeline
有了Pipeline的帮助,我们处理训练集数据和训练模型时候就只要一行的代码。 而平时,从数据处理到建模,我们可能会需要很多行的代码,这样会让整个notebook看起来很凌乱,而且在回去检查时候也特别麻烦。 同时,我们也可以将它应用到其他未处理的数据上,例如这个例子中的验证集,让管道自动帮我们时间验证集的数据处理。 不然的话,我们就得手动复制粘贴同样的代码,再逐行修改。
from sklearn.metrics import mean_absolute_error
#打包数据预处理和建模代码
my_pipeline = Pipeline(steps=[('preprocessor', preprocessor),
('model', model)])
# 对训练数据进行预处理和建模
my_pipeline.fit(X_train, y_train)
# 对验证集数据进行预处理和建模
preds = my_pipeline.predict(X_valid)
# 模型评估
score = mean_absolute_error(y_valid, preds)
print('MAE:', score)
查看Pipeline内容
# 查看整个pipeline
my_pipeline.steps
#查看第一步的全部内容
my_pipeline.steps[0]
#查看第一步的处理过程
my_pipeline[0]
pipeline和交叉验证的组合使用
from sklearn.model_selection import cross_val_score
# Multiply by -1 since sklearn calculates *negative* MAE
scores = -1 * cross_val_score(my_pipeline, X, y,
cv=5,
scoring='neg_mean_absolute_error')
print("MAE scores:\n", scores)
参考链接
Pipeline scikit-learn 官方文档链接:https://scikit-learn.org/stable/modules/compose.html#combining-estimators Pipeline | Kaggle:https://www.kaggle.com/code/alexisbcook/pipelines Cross-Validation | Kaggle:https://www.kaggle.com/code/alexisbcook/cross-validation/tutorial
其来无迹其往无崖 《天龙八部2》手游无崖子设定曝光
地图、资源包与数据包安装教程