1.pipeline清理建模代码
我们先看看常规建模步骤是怎么样的?
1 处理数据 2 选择模型 3 预测 4 评估
每一步都十分的繁琐,如果我们照常这么写下去,代码会十分长且不易懂。
但是python里面有个叫pipeline的东西,能把预处理与建模步骤打包在一起,使得代码精简美观。
(也有个make_pipeline,步骤会简单些)
一般情况下,通过三个步骤来使用pipelines:
步骤1:定义处理步骤
与pipeline将预处理与建模步骤打包一样,我们使用ColumnTransformer类来将不同的步骤打包在一起。下面的代码做了两件事情:
- 填充缺失数据为数值类型(用均值等方法填充数值类型数据)
- 用
one-hot编码来填充分类缺失数据


from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
# 预处理数值类型数据
numerical_transformer = SimpleImputer(strategy='constant')
# 预处理分类数据
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# 将处理步骤打包
preprocessor = ColumnTransformer(
transformers=[
('num', numerical_transformer, numerical_cols),
('cat', categorical_transformer, categorical_cols)
])View Code
ColumnTransformer是用于对特征的处理,功能是针对不同的列做不同的处理,最终输出各自结果的合集。
步骤2:定义模型
步骤3:创建和评估Pipeline
我们在调用predict()指令时使用的X_valid中包含未经处理的特征值,pipeline会在预测前自动进行预处理。(然而,如果不使用pipeline,在预测前,我们要对验证数据进行预处理)。


from sklearn.metrics import mean_absolute_error
# 在pipeline中打包预处理和建模代码
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)View Code
2.pipeline应用于交叉验证
交叉验证的应用前提:
- 对于小数据集,额外的计算并不是什么大事,你应该进行交叉验证。
- 对于较大的数据集,一个验证数据集就够了。你的代码将会执行得更快,有足够的数据就没必要复用数据。
步骤1:处理数据和选择模型(使用前面相同的数据)


my_pipeline = Pipeline(steps=[('preprocessor', SimpleImputer()),
('model', RandomForestRegressor(n_estimators=50,
random_state=0))
])View Code
步骤2:预测和评估


from sklearn.model_selection import cross_val_score
# 乘以-1,因为sklearn计算得到的是负MAE值(neg_mean_absolute_error)
scores = -1 * cross_val_score(my_pipeline, X, y,
cv=5,
scoring='neg_mean_absolute_error')View Code
最后算出score的平均值即可得出模型的好坏。
















