8.Using Categorical Data with One Hot Encoding

本教程是机器学习系列的一部分。 在此步骤中,您将了解“分类”变量是什么,以及处理此类数据的最常用方法。

Introduction

分类数据是仅采用有限数量值的数据。

例如,如果人们回答一项关于他们拥有哪种品牌汽车的调查,结果将是明确的(因为答案将是本田,丰田,福特,无等等)。 答案属于一组固定的类别。

如果您尝试将这些变量插入Python中的大多数机器学习模型而不首先“编码”它们,则会出现错误。 在这里,我们将展示最流行的分类变量编码方法。

One-Hot Encoding : The Standard Approach for Categorical Data

One-Hot Encoding是最普遍的方法,除非你的分类变量具有大量的值,否则它的效果非常好(例如,对于变量超过15个不同值的变量,你通常不会这样做。在数值较少的情况下它是一个糟糕的选择,尽管情况有所不同。)

One-Hot Encoding创建新的(二进制)列,指示原始数据中每个可能值的存在。 让我们通过一个例子来解决。

Imgur

原始数据中的值为红色,黄色和绿色。 我们为每个可能的值创建一个单独的列。 只要原始值为红色,我们在红色列中放置1。

Example

我们在代码中看到这个。 我们将跳过基本数据设置代码,因此您可以从拥有train_predictors,test_predictors 的DataFrames位置开始。 该数据包含住房特征。 您将使用它们来预测房屋价格,房屋价格存储在称为目标的系列中。

【1】

# Read the data
import pandas as pd
train_data = pd.read_csv('../input/train.csv')
test_data = pd.read_csv('../input/test.csv')# Drop houses where the target is missing
train_data.dropna(axis=0, subset=['SalePrice'], inplace=True)target = train_data.SalePrice# Since missing values isn't the focus of this tutorial, we use the simplest
# possible approach, which drops these columns. 
# For more detail (and a better approach) to missing values, see
# https://www.kaggle.com/dansbecker/handling-missing-values
cols_with_missing = [col for col in train_data.columns if train_data[col].isnull().any()]                                  
candidate_train_predictors = train_data.drop(['Id', 'SalePrice'] + cols_with_missing, axis=1)
candidate_test_predictors = test_data.drop(['Id'] + cols_with_missing, axis=1)# "cardinality" means the number of unique values in a column.
# We use it as our only way to select categorical columns here. This is convenient, though
# a little arbitrary.
low_cardinality_cols = [cname for cname in candidate_train_predictors.columns if candidate_train_predictors[cname].nunique() < 10 andcandidate_train_predictors[cname].dtype == "object"]
numeric_cols = [cname for cname in candidate_train_predictors.columns if candidate_train_predictors[cname].dtype in ['int64', 'float64']]
my_cols = low_cardinality_cols + numeric_cols
train_predictors = candidate_train_predictors[my_cols]
test_predictors = candidate_test_predictors[my_cols]

Pandas为每个列或系列分配数据类型(称为dtype)。 让我们从预测数据中看到随机的dtypes样本:

【2】

train_predictors.dtypes.sample(10)
Heating          object
CentralAir       object
Foundation       object
Condition1       object
YrSold            int64
PavedDrive       object
RoofMatl         object
PoolArea          int64
EnclosedPorch     int64
KitchenAbvGr      int64
dtype: object

对象表示一列有文本(理论上可能有其他东西,但这对我们的目的来说并不重要)。 对这些“对象”列进行one-hot encode是最常见的,因为它们不能直接插入大多数模型中。 Pandas提供了一个名为get_dummies的便捷功能,可以获得one-hot encodings。 这样叫:

[3]

one_hot_encoded_training_predictors = pd.get_dummies(train_predictors)

或者,您可以删除分类。 为了了解这些方法的比较,我们可以计算两组可选预测构建的模型的平均绝对误差:

  1.      One-hot encoded分类以及数字预测变量
  2.      数值预测,我们删除分类。

One-hot encoding通常有所帮助,但它会根据具体情况而有所不同。 在这种情况下,使用one-hot encoded变量似乎没有任何的好处。

 

[4]

from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestRegressordef get_mae(X, y):# multiple by -1 to make positive MAE score instead of neg value returned as sklearn conventionreturn -1 * cross_val_score(RandomForestRegressor(50), X, y, scoring = 'neg_mean_absolute_error').mean()predictors_without_categoricals = train_predictors.select_dtypes(exclude=['object'])mae_without_categoricals = get_mae(predictors_without_categoricals, target)mae_one_hot_encoded = get_mae(one_hot_encoded_training_predictors, target)print('Mean Absolute Error when Dropping Categoricals: ' + str(int(mae_without_categoricals)))
print('Mean Abslute Error with One-Hot Encoding: ' + str(int(mae_one_hot_encoded)))
Mean Absolute Error when Dropping Categoricals: 18350
Mean Abslute Error with One-Hot Encoding: 18023

Applying to Multiple Files

到目前为止,您已经对您的训练数据进行了one-hot encoded。 当你有多个文件(例如测试数据集,或者你想要预测的其他数据)时怎么办? Scikit-learn对列的排序很敏感,因此如果训练数据集和测试数据集未对齐,则结果将是无意义的。 如果分类在训练数据中与测试数据具有不同数量的值,则可能发生这种情况。

使用align命令确保测试数据的编码方式与训练数据相同:

【5】

one_hot_encoded_training_predictors = pd.get_dummies(train_predictors)
one_hot_encoded_test_predictors = pd.get_dummies(test_predictors)
final_train, final_test = one_hot_encoded_training_predictors.align(one_hot_encoded_test_predictors,join='left', axis=1)

align命令确保列在两个数据集中以相同的顺序显示(它使用列名来标识每个数据集中的哪些列对齐。)参数join ='left'指定我们将执行等效的SQL左连接。 这意味着,如果有一列显示在一个数据集而不是另一个数据集中,我们将保留我们的训练数据中的列。 参数join ='inner'将执行SQL数据库调用内连接的操作,仅保留两个数据集中显示的列。 这也是一个明智的选择。

Conclusion

世界充满了分类数据。 如果您知道如何使用这些数据,那么您将成为一名更有效的数据科学家。 当您开始使用cateogircal数据进行更复杂的工作时,这些资源将非常有用。

  1.      管道:将模型部署到生产就绪系统本身就是一个主题。 虽然one-hot encoding仍然是一种很好的方法,但您的代码需要以特别强大的方式构建。 Scikit-learn管道是一个很好的工具。 Scikit-learn提供了class for one-hot encoding,可以将其添加到管道中。 不幸的是,它不处理文本或对象值,这是一个常见的用例。
  2.      应用于深度学习的文本:Keras和TensorFlow具有one-hot encoding的功能,这对于处理文本很有用。
  3.      具有多个值的分类:Scikit-learn的FeatureHasher使用散列技巧来存储高维数据。 这将为您的建模代码增加一些复杂性。

Your Turn

使用one-hot encoding允许课程项目中的分类。 然后在X数据中添加一些分类列。 如果选择正确的变量,您的模型将会有相当大的改进。 完成后,单击此处返回学习机器学习,您可以继续改进模型。

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

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

相关文章

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

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

*【HDU - 5707】Combine String(dp)

题干&#xff1a; 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协议 在世界上各地&#xff0c;各种各样的电脑运行着各自不同的操作系统为大家服务&#xff0c;这些电脑在表达同一种信息的时候所使用的方法是千差万别。就好像圣经中上帝打乱 了各地人的口音&#xff0c;让他们无法合作一样。计算机使用者意识到&#xff0c;…

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

题干&#xff1a; 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系统软件之不同对于中关村在线的网友来说&#xff0c;PC系统应该都不陌生&#xff0c;而且分分钟重装的水准。但在笔者过往的服务器装机经验中&#xff0c;可谓是一部千年血泪史。服务器和PC系统差别还是很大的。现在的PC系统多是windows7和windows10&#xff0c;而在…

9.XGBoost

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

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

题干&#xff1a; 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脚本像下面&#xff1a;成功()函数的AJAX GET请求function FillCity() {var stateID $("#ddlState").val();$.ajax({url: Url.Action("Employee", "Index"),type: "GET",dataType: "json",data:…

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

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

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

题干&#xff1a; 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日停服维护说明】亲爱的设计师&#xff1a;为了给设计师们提供更好的游戏体验&#xff0c;光启市将于7月16日(周五)00:00进行预计5小时的停服维护&#xff0c;可…

10.Partial Dependence Plots

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

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

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

0.《Apollo自动驾驶工程师技能图谱》

【新年礼物】开工第一天&#xff0c;送你一份自动驾驶工程师技能图谱&#xff01; 布道团队 Apollo开发者社区 1月 2日 AI时代到来&#xff0c;人才的缺乏是阻碍行业大步发展的主要因素之一。Apollo平台发布以来&#xff0c;我们接触到非常多的开发者他们并不是专业自动驾驶领…

【HDU - 1116】【POJ - 1386】Play on Words(判断半欧拉图,欧拉通路)

题干&#xff1a; Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve it to open that doors. Because there is no other way to open the doors, the puzzle is very important for us. There is a large number…

11.Pipelines

本教程是ML系列的一部分。 在此步骤中&#xff0c;您将了解如何以及为何使用管道清理建模代码。 What Are Pipelines 管道是保持数据处理和建模代码有序的简单方法。 具体来说&#xff0c;管道捆绑了预处理和建模步骤&#xff0c;因此您可以像使用单个包一样使用整个捆绑包。…

ubuntu服务器创建共享文件夹,Ubuntu samba安装创建共享目录及使用

Ubuntu samba更新了很多版本更新&#xff0c;我本人认为Ubuntu samba是很好使的文件系统&#xff0c;在此向大家推荐。如今技术不断更新&#xff0c;各种使用文件都已经淘汰。我认为还是有很不错的如Ubuntu samba值得大家来运用。一. Ubuntu samba的安装:sudo apt-get insall s…

【POJ - 2337】Catenyms(欧拉图相关,欧拉通路输出路径,tricks)

题干&#xff1a; A catenym is a pair of words separated by a period such that the last letter of the first word is the same as the last letter of the second. For example, the following are catenyms: dog.gophergopher.ratrat.tigeraloha.alohaarachnid.dog A…

12.Cross-Validation

本教程是ML系列的一部分。 在此步骤中&#xff0c;您将学习如何使用交叉验证来更好地衡量模型性能。 What is Cross Validation 机器学习是一个迭代过程。 您将面临关于要使用的预测变量&#xff0c;要使用的模型类型&#xff0c;提供这些模型的参数等的选择。我们通过测量各…