欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

实战墨尔本房价预测:使用sklearn pipeline进行机器学习

最编程 2024-02-03 20:55:12
...

问题描述

我们在运用pandas写数据预处理时,数据清洗和建模部分有时候会觉得写的比较乱,维护和修改较为麻烦。不过,sklearn库中的Pipeline(流水线)较好地解决了这个问题,
比如原来代码这样的:

from sklearn.preprocessing import OneHotEncoder

object_cols = [...] #随便举个例子
OH_encoder = OneHotEncoder(handle_unknown='ignore', sparse=False)
OH_cols_train = pd.DataFrame(OH_encoder.fit_transform(X_train[object_cols]))
OH_cols_valid = pd.DataFrame(OH_encoder.transform(X_valid[object_cols]))

OH_cols_train.index = X_train.index
OH_cols_valid.index = X_valid.index

num_X_train = X_train.drop(object_cols, axis=1)
num_X_valid = X_valid.drop(object_cols, axis=1)

一个简单的onehot编码就要写那么多了,如果是较为复杂的预处理,代码的维护就比较复杂啦(doge)
但是使用了pipeline后,代码就简单了很多

categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')), 
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

这个让我想起了torch中的类似用法

transforms.Compose([transforms.CenterCrop(50),
    				transforms.Resize(256)
    				transforms.ToTensor(),])

感觉代码瞬间就高大上了是不是(doge)

基于pipeline的机器学习实战

我们将详细讲解基于pipeline的机器学习实战,代码的主体来自于kaggle官方教程,源链接为
kaggle官方pipeline
本文将更加细致地介绍各个方法,并且做出一些合理(qi guai)的扩充。
数据下载:
百度网盘链接:https://pan.baidu.com/s/1rMVxL1ThcvHzSS2s8hmOrw
提取码:whqf
数据集大概这样
前半
后半
1.环境和数据准备,没啥说的

import pandas as pd
from sklearn.model_selection import train_test_split

data = pd.read_csv('melb.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)

2.确定数据类型
由于我们的数据集中含有numerical(数值)的数据和categorical(类别)的数据,他们预处理的方式不一样,所以要分开。
(对于萌新,我解释一下,numerical是数字,像1,2,3这样的;categorical就是像猫,狗之类的数据,是描述类别的数据)

# "Cardinality" means the number of unique values in a column
# Select categorical columns with relatively low cardinality (convenient but arbitrary)
cardinality = 10
categorical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].nunique() < cardinality 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()

原文作者在这边的代码只能做类别不超过10的,因为他在选categorical数据的时候把多于10的洗掉了。
3.查看缺失数据
属于传统艺能了是(doge)

cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any()]
print(cols_with_missing) # 结果是['Car', 'BuildingArea', 'YearBuilt']

4.数据预处理(作为强迫症患者流下了感动的泪水)

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),      # 名字,transformer,应用的列
        ('cat', categorical_transformer, categorical_cols)
    ])

别急,慢慢来。第一个代码块:

numerical_transformer = SimpleImputer(strategy='constant')

使用常数来填空的取值,默认是0。
另外,strategy还能取 mean-均值,median-中位数,most_frequent-最频繁的那个。

pipeline,他来了!

categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')), 
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

step后面的列表表示流水线里面的函数的顺序,里面的数据结构是
(这个步骤的名字,操作/函数)
在这边,就是先执行SimpleImputer(strategy=‘most_frequent’),再执行
OneHotEncoder(handle_unknown=‘ignore’)

最后是这个神奇的函数

preprocessor = ColumnTransformer(
    transformers=[
        ('num', numerical_transformer, numerical_cols),      # 名字,transformer,应用的列
        ('cat', categorical_transformer, categorical_cols)
    ])

如果说pipeline在这边的结构像串行的结构,这边就像并行。ColumnTransformer函数把numerical_cols,就是
对numerical数据使用numerical_transformer函数,
对categorical数据使用categorical_transformer函数,
整体数据结构是
(名字,操作函数,作为操作对象的列)

5.建模与评估
建模的时候,我们继续使用pipeline,把预处理和模型放一起。

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error

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

# Bundle preprocessing and modeling code in a 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)

至此,我们的使用pipeline改进代码结构的工作已经结束了,以后会写一个pipeline进阶,介绍更多的相关函数和操作。