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_splitmelb_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_splitX_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 SimpleImputermy_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并且包含缺失值的列,您就可以添加分类变量,这些变量是表示类别的非数字数据(例如房屋所在社区的名称)。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/440338.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

打开电脑计算机超级慢,手把手教你电脑开机慢怎么办

等到花都谢了,你怎么还不开机?这电脑开机真是离奇的慢,有心将它换了,奈何兜里空空。凑合着用又无法忍受这种煎熬。其实你只需要用鼠标点几下就可以不用等待这漫长的开机过程了。高铁,飞机,网络,…

【POJ - 1486】Sorting Slides(思维建图,二分图求必须边,关建边,图论)

题干: Professor Clumsey is going to give an important talk this afternoon. Unfortunately, he is not a very tidy person and has put all his transparencies on one big heap. Before giving the talk, he has to sort the slides. Being a kind of minima…

用OpenSSL编写SSL,TLS程序

http://zhoulifa.bokee.com/6134045.html http://blog.sina.com.cn/s/blog_86ca13bb0100vaph.html http://blog.chinaunix.net/uid-26575352-id-3048856.html 一、简介: SSL(SecureSocket Layer)是netscape公司提出的主要用于web的安全通信标准,分为2.0版和3.0版.TLS(Transport…

信息技术计算机伦理与安全教案,龙教版信息技术七年级下册第7课 安全与道德 教案...

ID:9954219分类:全国,2019资源大小:228KB资料简介:题 目第七课 安全与道德总课时1设计来源自我设计教学时间教材分析这节课计算机与网络安全部分定义介绍和叙述较多,所以为了避免枯燥可以设计课件和并准备病毒计算机安全报道的视频、多媒体讲解、图片等…

【HDU - 5706】GirlCat(bfs)

题干: As a cute girl, Kotori likes playing Hide and Seek with cats particularly. Under the influence of Kotori, many girls and cats are playing Hide and Seek together. Koroti shots a photo. The size of this photo is nmnm, each pixel of the ph…

8.Using Categorical Data with One Hot Encoding

本教程是机器学习系列的一部分。 在此步骤中,您将了解“分类”变量是什么,以及处理此类数据的最常用方法。 Introduction 分类数据是仅采用有限数量值的数据。 例如,如果人们回答一项关于他们拥有哪种品牌汽车的调查,结果将是明…

iPhone换屏幕测试软件,怎样检验iPhone是否更换过屏幕?

原标题:怎样检验iPhone是否更换过屏幕?关注下图公众号,鉴定苹果手机真假↓↓↓购买新手机时,到手后会想手机各零部件是否是正品原装,就好比屏幕是否原装屏!入手一部iPhone新机的时候,该如何检验…

*【HDU - 5707】Combine String(dp)

题干: Given three strings aa, bb and cc, your mission is to check whether cc is the combine string of aa and bb. A string cc is said to be the combine string of aa and bb if and only if cc can be broken into two subsequences, when you read the…

《TCP/IP详解》学习笔记(一):基本概念

为什么会有TCP/IP协议 在世界上各地,各种各样的电脑运行着各自不同的操作系统为大家服务,这些电脑在表达同一种信息的时候所使用的方法是千差万别。就好像圣经中上帝打乱 了各地人的口音,让他们无法合作一样。计算机使用者意识到,…

【POJ - 3272】Cow Traffic(dp,建反向图,DAG拓扑图)

题干: The bovine population boom down on the farm has caused serious congestion on the cow trails leading to the barn. Farmer John has decided to conduct a study to find the bottlenecks in order to relieve the traffic jams at milking time. The…

pc服务器不同型号,服务器与PC系统软件之不同

服务器与PC系统软件之不同对于中关村在线的网友来说,PC系统应该都不陌生,而且分分钟重装的水准。但在笔者过往的服务器装机经验中,可谓是一部千年血泪史。服务器和PC系统差别还是很大的。现在的PC系统多是windows7和windows10,而在…

9.XGBoost

本教程是机器学习系列的一部分。 在此步骤中,您将学习如何使用功能强大的xgboost库构建和优化模型。 What is XGBoost XGBoost是处理标准表格数据的领先模型(您在Pandas DataFrames中存储的数据类型,而不是像图像和视频这样的更奇特的数据类…

*【HDU - 5711】Ingress(tsp旅行商问题,优先队列贪心,状压dp,floyd最短路,图论)

题干: Brickgao, who profited from your accurate calculating last year, made a great deal of money by moving bricks. Now he became gay shy fool again and recently he bought an iphone and was deeply addicted into a cellphone game called Ingress. …

ajax get请求成功,成功()函数的AJAX GET请求

后不叫我有一个jQuery的AJAX脚本像下面:成功()函数的AJAX GET请求function FillCity() {var stateID $("#ddlState").val();$.ajax({url: Url.Action("Employee", "Index"),type: "GET",dataType: "json",data:…

《TCP/IP详解》学习笔记(二):数据链路层

数据链路层有三个目的: 为IP模块发送和 接收IP数据报。为ARP模块发送ARP请求和接收ARP应答。为RARP发送RARP请 求和接收RARP应答ip大家都听说过。至于ARP和RARP,ARP叫做地址解析协议,是用IP地址换MAC地址的一种协议,而RARP则叫…

【POJ - 2762】Going from u to v or from v to u?(Tarjan缩点,树形dp 或 拓扑排序,欧拉图相关)

题干: In order to make their sons brave, Jiajia and Wind take them to a big cave. The cave has n rooms, and one-way corridors connecting some rooms. Each time, Wind choose two rooms x and y, and ask one of their little sons go from one to the o…

《TCP/IP详解》学习笔记(三):IP协议、ARP协议

把这三个协议放到一起学习是因为这三个协议处于同一层,ARP 协议用来找到目标主机的 Ethernet 网卡 Mac 地址,IP 则承载要发 送的消息。数据链路层可以从 ARP 得到数据的传送信息,而从 IP 得到要传输的数据信息。 IP 协议 IP 协议是 TCP/IP 协议的核心,所有的 TCP,UDP,IMCP,IGCP…

光与夜之恋服务器维护中,光与夜之恋7月16日停服维护说明 维护详情一览

光与夜之恋7月16日停服维护说明维护详情一览。光与夜之恋7月16日停服维护更新了哪些内容?我们去了解一下。【7月16日停服维护说明】亲爱的设计师:为了给设计师们提供更好的游戏体验,光启市将于7月16日(周五)00:00进行预计5小时的停服维护,可…

10.Partial Dependence Plots

本教程是ML系列的一部分。 在此步骤中,您将学习如何创建和解释部分依赖图,这是从模型中提取洞察力的最有价值的方法之一。 What Are Partial Dependence Plots 有人抱怨机器学习模型是黑盒子。这些人会争辩说我们无法看到这些模型如何处理任何给定的数据…

springboot监控服务器信息,面试官:聊一聊SpringBoot服务监控机制

目录前言任何一个服务如果没有监控,那就是两眼一抹黑,无法知道当前服务的运行情况,也就无法对可能出现的异常状况进行很好的处理,所以对任意一个服务来说,监控都是必不可少的。就目前而言,大部分微服务应用…