ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Kaggle学习笔记之Pipelines

2022-03-18 22:07:19  阅读:198  来源: 互联网

标签:full Pipelines Kaggle 笔记 cols 管道 train data 预处理


Kaggle中级机器学习 - Pipelines

Pipeline:https://sklearn.apachecn.org/#/docs/master/38

ColumnTransformer:https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html

通过预处理来部署(甚至测试)复杂模型的关键技能:管道机制

目录

使用管道的优势

  • 更简洁的代码:在预处理的每个步骤中对数据进行核算可能会变得混乱。 使用管道就不需要在每一步手动跟踪训练和验证数据。
  • 更少的错误:错误应用步骤或忘记预处理步骤的机会更少。
  • 更容易生产化:将模型从原型转换为可大规模部署的模型可能非常困难。 我们不会在这里讨论许多相关的问题,但管道可以提供帮助。
  • 模型验证的更多选项:您将在下一个教程中看到一个示例,其中涵盖了交叉验证。
import pandas as pd
from sklearn.model_selection import train_test_split

# Read the data
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')

# Separate target from predictors
y = data.Price
X = data.drop(['Price'], axis=1)

# Divide data into training and validation subsets
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)

# "Cardinality" means the number of unique values in a column
# Select categorical columns with relatively low cardinality (convenient but arbitrary)
categorical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].nunique() < 10 and 
                        X_train_full[cname].dtype == "object"]

# Select numerical columns
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()

三步构建完整的管道

Step 1:定义预处理步骤

使用 ColumnTransformer 类将不同的预处理步骤打包到一起。包括:

  • 插补数值列的缺失值
  • 插补分类变量列的缺失值并应用one-hot编码。
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder

# Preprocessing for numerical data
numerical_transformer = SimpleImputer(strategy='constant')

# Preprocessing for categorical data 
categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

# Bundle preprocessing for numerical and categorical data
preprocessor = ColumnTransformer(
    transformers=[
        ('num', numerical_transformer, numerical_cols),
        ('cat', categorical_transformer, categorical_cols)
    ])

Step 2:定义模型

使用RandomForestRegressor类定义一个随机森林模型。

from sklearn.ensemble import RandomForestRegressor

model = RandomForestRegressor(n_estimators=100, random_state=0)

Step 3:创建和评估管道

使用Pipeline类定义管道,将预处理和建模步骤打包。

  • 使用管道,我们预处理训练数据并将模型拟合到一行代码中。 (相比之下,如果没有管道,我们必须在单独的步骤中进行插补、one-hot 编码和模型训练。如果我们必须同时处理数字变量和分类变量,这将变得特别混乱!)
  • 通过管道,我们将 X_valid 中未处理的特征提供给 predict() 命令,管道在生成预测之前自动预处理这些特征。 (但是,如果没有管道,我们必须记住在进行预测之前对验证数据进行预处理。)
from sklearn.metrics import mean_absolute_error

# Bundle preprocessing and modeling code in a pipeline
my_pipeline = Pipeline(steps=[('preprocessor', preprocessor),
                              ('model', model)
                             ])

# Preprocessing of training data, fit model 
my_pipeline.fit(X_train, y_train)

# Preprocessing of validation data, get predictions
preds = my_pipeline.predict(X_valid)

# Evaluate the model
score = mean_absolute_error(y_valid, preds)
print('MAE:', score)
MAE: 160679.18917034855

总结

管道对于清理机器学习代码和避免错误很有价值,对于具有复杂数据预处理的工作流尤其有用。

标签:full,Pipelines,Kaggle,笔记,cols,管道,train,data,预处理
来源: https://www.cnblogs.com/ikventure/p/16023766.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有