Sklearn中Pipeline的用法介绍 (使用Pipelines简化Python机器学习代码)

29 篇文章 4 订阅

Pipeline模块介绍

Pipelines ,直译是“管道“, 类似于流水线的意思,可以将数据预处理和建模流程封装起来。
在数据处理过程中,很多步骤都是重复或者类似的,比如特征选择处理、归一化、分类等等,pipeline就可以实现以下几点好处:

  1. 简化代码:数据预处理过程是很繁杂凌乱的,pipeline 可以直接将步骤封装成完整的工作流,避免了代码重复。
  2. 更少出Bug:流程规范化了,就能在避免在建模过程中漏掉某个步骤。
  3. 更易于生产/复制:将建好的模型应用到实际数据,或者大规模部署到不同的数据集时,过程会非常繁琐,我们不需要在处理很多的问题,但Pipline可以帮助我们省略这些重复的过程,直接调用fit和predict来对所有算法模型进行训练和预测。
  4. 简化模型验证过程:比如将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

步骤一:确定预处理步骤

  1. 处理数值型变量的缺失值
  2. 处理分类型变量的缺失值并且使用独热编码
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

  • 9
    点赞
  • 80
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
sklearnpipeline机器学习非常方便的工具,可以将多个预处理方法和模型组合成一个整体,用于训练和测试数据集。下面是一个简单的示例代码: ```python from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # 导入数据集并划分训练集和测试集 iris = load_iris() X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state=0) # 创建 Pipeline 对象,包含三个步骤:缺失值填充、特征缩放和 PCA 降维 pipe = Pipeline([ ('imputer', SimpleImputer(strategy='mean')), ('scaler', StandardScaler()), ('pca', PCA(n_components=2)) ]) # 使用 Pipeline 对象对训练集进行预处理和训练 X_train_transformed = pipe.fit_transform(X_train, y_train) # 使用 Pipeline 对象对测试集进行预处理和预测 score = pipe.score(X_test, y_test) print(score) # 把预处理和模型训练组合成一个 Pipeline 对象 clf = Pipeline([ ('preprocessing', pipe), ('classifier', LogisticRegression()) ]) # 使用 Pipeline 对象对训练集进行预处理和训练 clf.fit(X_train, y_train) # 使用 Pipeline 对象对测试集进行预处理和预测 score = clf.score(X_test, y_test) print(score) ``` 这个示例,我们使用Pipeline 对象来组合三个步骤:缺失值填充、特征缩放和 PCA 降维。我们还使用了另一个 Pipeline 对象来组合预处理和模型训练。最终,我们使用这个对象对测试集进行预处理和预测,并计算了预测的准确率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值