【Python实例第4讲】填补缺失值

机器学习训练营——机器学习爱好者的自由交流空间(qq 群号:696721295)

在这个例子里,我们向大家展示填补缺失值比丢弃它们得到的结果更好。但是请注意,缺失值填补并不总会改善预测结果,所以请使用交叉验证评价。有的时候,丢弃缺失行或使用标记值反而更有效。
一般时候,缺失值可以用均值、中位数或众数代替。当变量较多时,用中位数代替是一种稳健的方法。在本例中,填补将有助于分类器接近原始分数。

首先,导入必需的模块。

import numpy as np

from sklearn.datasets import load_boston
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Imputer
from sklearn.model_selection import cross_val_score

导入模块后,从numpy工具包生成模拟数据集。

rng = np.random.RandomState(0)

使用函数RandomState获得随机数生成器。0为随机种子,只要随机种子相同,产生的随机数序列就相同。

加载“波士顿房价”数据集,该数据集在【Python实例第1讲】介绍过。

dataset = load_boston()
X_full, y_full = dataset.data, dataset.target
n_samples = X_full.shape[0]
n_features = X_full.shape[1]
print(X_full.shape)

第一步:估计完整数据集的分数

创建一个由100棵树组成的随机森林估计量estimator,随机状态是随机数生成器的种子0.一个随机森林是一个拟合多棵分类决策树的估计量,它使用平均化的办法来改善预测准确率,控制过度拟合。构建决策树的子样本是原始样本的bootstrap样本。

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

使用交叉验证法评价分数,取分数的平均值,保留小数点后两位打印出来。

score = cross_val_score(estimator, X_full, y_full).mean()
print("Score with the entire dataset = %.2f" % score)

第二步:在75%的数据行里增加缺失值

missing_rate = 0.75
n_missing_samples = int(np.floor(n_samples * missing_rate))
missing_samples = np.hstack((np.zeros(n_samples - n_missing_samples,
                                      dtype=np.bool),
                             np.ones(n_missing_samples,
                                     dtype=np.bool)))
rng.shuffle(missing_samples)
missing_features = rng.randint(0, n_features, n_missing_samples)

第三步:估计不包括缺失行的子集分数

X_filtered = X_full[~missing_samples, :]
y_filtered = y_full[~missing_samples]
estimator = RandomForestRegressor(random_state=0, n_estimators=100)
score = cross_val_score(estimator, X_filtered, y_filtered).mean()
print("Score without the samples containing missing values = %.2f" % score)

第四步:估计填补缺失值后的数据集分数

将缺失值处标记为0, 再将数据集里标记为0的项,用该项所在列的均值代替。由于列表示特征,此即用该特征的均值代替缺失值。最后,在填补后的数据集上计算分数。

X_missing = X_full.copy()
X_missing[np.where(missing_samples)[0], missing_features] = 0
y_missing = y_full.copy()
estimator = Pipeline([("imputer", Imputer(missing_values=0,
                                          strategy="mean",
                                          axis=0)),
                      ("forest", RandomForestRegressor(random_state=0,
                                                       n_estimators=100))])
score = cross_val_score(estimator, X_missing, y_missing).mean()
print("Score after imputation of the missing values = %.2f" % score)

让我们来比较三种情况下的分数值:

Score with the entire dataset = 0.56

Score without the samples containing missing values = 0.48

Score after imputation of the missing values = 0.57

由此可见,填补后的分值更加接近完整分值。

阅读更多精彩内容,请关注微信公众号:统计学习与大数据

猜你喜欢

转载自blog.csdn.net/wong2016/article/details/82697309