Kaggle学习笔记之Pipelines

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

总结

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

posted @ 2022-03-18 21:52  ikventure  阅读(84)  评论(0编辑  收藏  举报