7.Handling Missing Values

本教程是学习机器学习课程的第2部分。 本教程选择了1级完成的位置,因此如果您从1级完成练习,您将获得最大的收益。

在此步骤中,您将学习三种处理缺失值的方法。 然后,您将学习如何比较这些方法在任何给定数据集上的有效性。

Introduction

数据可以通过多种方式以缺失值终止。 例如

  •      两卧室房子不包括第三间卧室有多大的答案
  •      接受调查的人可能会选择不分享收入

Python库将缺少的数字表示为nan,这是“not a number”的缩写。 您可以检测哪些单元格缺少值,然后使用以下命令计算每列中有多少单元格:

missing_val_count_by_column =(data.isnull().sum())
print(missing_val_count_by_column [missing_val_count_by_column]> 0)

如果您尝试使用缺少值的数据构建模型,则大多数库(包括scikit-learn)都会给您一个错误。 因此,您需要选择以下策略之一。

Solutions

1)A Simple Option:Drop Columns with Missing Values

如果您的数据位于名为original_data的DataFrame中,则可以删除缺少值的列。 一种方法是

data_without_missing_values = original_data.dropna(axis=1)

在许多情况下,您将同时拥有训练数据集和测试数据集。 您需要在两个DataFrame中删除相同的列。 在那种情况下,你会写

cols_with_missing = [col for col in original_data.columns 
                                 if original_data[col].isnull().any()]
redued_original_data = original_data.drop(cols_with_missing, axis=1)
reduced_test_data = test_data.drop(cols_with_missing, axis=1)

如果这些列具有有用信息(在未丢失的位置),则在删除列时,模型将失去对此信息的访问权限。 此外,如果您的测试数据在您的训练数据有信息的地方缺少值,则会导致错误。

所以,它通常不是最好的解决方案。 但是,当缺少列中的大多数值时,它可能很有用

2)A Better Option:Imputation

插值是用一些数字填充缺失值。 在大多数情况下,估算值并不完全正确,但它通常会提供比完全删除列更准确的模型。
是这样完成的:

from sklearn.impute import SimpleImputer
my_imputer = SimpleImputer()
data_with_imputed_values = my_imputer.fit_transform(original_data)

默认情况为插入平均值。 统计学家已经研究了更复杂的策略,但是一旦将结果插入复杂的机器学习模型,那些复杂的策略通常没有任何好处。

关于Imputation的一个(很多)好处是它可以包含在scikit-learn Pipeline中。 管道简化了模型构建,模型验证和模型部署。

3)An Extension To Imputation

估算是标准方法,通常效果很好。 但是,估算值可能在系统上高于或低于其实际值(未在数据集中收集)。 或者具有缺失值的行是唯一的。 在这种情况下,您的模型会通过考虑最初缺少哪些值来做出更好的预测。 以下是它的外观:

# make copy to avoid changing original data (when Imputing)
new_data = original_data.copy()

# make new columns indicating what will be imputed
cols_with_missing = (col for col in new_data.columns 
                                 if new_data[col].isnull().any())
for col in cols_with_missing:
    new_data[col + '_was_missing'] = new_data[col].isnull()

# Imputation
my_imputer = SimpleImputer()
new_data = pd.DataFrame(my_imputer.fit_transform(new_data))
new_data.columns = original_data.columns

在某些情况下这个方法会有效改善结果,在其它情况下,这可能会根本没有帮助。

Example(Comparing All Solutions)

我们将看到从墨尔本房屋数据预测房价的例子。 要掌握缺失值处理,请复制此笔记并使用Iowa Housing数据重复相同的步骤。 在标题菜单的“数据”部分中查找有关这两者的信息。

Basic Problem Set-up

[1]

import pandas as pd

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

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

melb_target = melb_data.Price
melb_predictors = melb_data.drop(['Price'], axis=1)

# For the sake of keeping the example simple, we'll use only numeric predictors. 
melb_numeric_predictors = melb_predictors.select_dtypes(exclude=['object'])

Create Function to Measure Quality of An Approach

我们将数据分为训练和测试。
我们加载了一个函数score_dataset(X_train,X_test,y_train,y_test)来比较不同方法与缺失值的质量。 此函数报告来自RandomForest的样本外MAE分数。

【2】

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

X_train, X_test, y_train, y_test = train_test_split(melb_numeric_predictors, 
                                                    melb_target,
                                                    train_size=0.7, 
                                                    test_size=0.3, 
                                                    random_state=0)

def score_dataset(X_train, X_test, y_train, y_test):
    model = RandomForestRegressor()
    model.fit(X_train, y_train)
    preds = model.predict(X_test)
    return mean_absolute_error(y_test, preds)

Get Model Score from Dropping Columns with Missing Values

【3】

cols_with_missing = [col for col in X_train.columns 
                                 if X_train[col].isnull().any()]
reduced_X_train = X_train.drop(cols_with_missing, axis=1)
reduced_X_test  = X_test.drop(cols_with_missing, axis=1)
print("Mean Absolute Error from dropping columns with Missing Values:")
print(score_dataset(reduced_X_train, reduced_X_test, y_train, y_test))
Mean Absolute Error from dropping columns with Missing Values:
187283.10974589147

Get Model Score from Imputation

【4】

from sklearn.impute import SimpleImputer

my_imputer = SimpleImputer()
imputed_X_train = my_imputer.fit_transform(X_train)
imputed_X_test = my_imputer.transform(X_test)
print("Mean Absolute Error from Imputation:")
print(score_dataset(imputed_X_train, imputed_X_test, y_train, y_test))
Mean Absolute Error from Imputation:
184651.6439862543

Get Score from Imputation with Extra Columns Showing What Was Imputed

【5】

imputed_X_train_plus = X_train.copy()
imputed_X_test_plus = X_test.copy()

cols_with_missing = (col for col in X_train.columns 
                                 if X_train[col].isnull().any())
for col in cols_with_missing:
    imputed_X_train_plus[col + '_was_missing'] = imputed_X_train_plus[col].isnull()
    imputed_X_test_plus[col + '_was_missing'] = imputed_X_test_plus[col].isnull()

# Imputation
my_imputer = SimpleImputer()
imputed_X_train_plus = my_imputer.fit_transform(imputed_X_train_plus)
imputed_X_test_plus = my_imputer.transform(imputed_X_test_plus)

print("Mean Absolute Error from Imputation while Track What Was Imputed:")
print(score_dataset(imputed_X_train_plus, imputed_X_test_plus, y_train, y_test))

Conclusion

通常,与丢弃这些列相比,输入缺失值允许我们改进模型。 通过跟踪估算的值,我们得到了额外的提升。

Your Turn

1)在数据集中查找一些缺少值的列。
2)使用Imputer类,以便可以输入缺失值
3)将具有缺失值的列添加到预测变量中。
如果找到正确的列,您可能会看到模型得分有所改善。 也就是说,lowa的数据没有很多缺少值的列。 因此,您是否看到此时的改进取决于您的模型的其他一些细节。
添加Imputer后,请继续使用这些列以用于将来的步骤。 最后,它将改进您的模型(在大多数其他数据集中,这是一个很大的改进)。

Keep Going

一旦添加了Imputer并且包含缺失值的列,您就可以添加分类变量,这些变量是表示类别的非数字数据(例如房屋所在社区的名称)。

猜你喜欢

转载自blog.csdn.net/cg129054036/article/details/82377738
今日推荐