数据预处理中使用toarray()与onehotencoding

我是机器学习的新手。我有一个疑问:为什么在这里使用onehotencoding时要用toarray(),而使用label encoding时却不需要?我完全不明白,请有人帮帮我。

from sklearn.preprocessing import LabelEncoder, OneHotEncoderlabel_encoder_x = LabelEncoder()x[:, 0] = label_encoder_x.fit_transform(x[:, 0])onehotencoder = OneHotEncoder(categorical_features= [0])x = onehotencoder.fit_transform(x).toarray()label_encoder_y = LabelEncoder()y = label_encoder_y.fit_transform(y)

回答:

正如文档中所述,OneHotEncoder默认会返回一个稀疏矩阵,这种格式不太直观。举个简单的例子:

>>> df   00  21  22  23  14  15  26  27  18  19  1onehotencoder = OneHotEncoder(categorical_features= [0])>>> onehotencoder.fit_transform(df[0].values.reshape(1,-1))<1x10 sparse matrix of type '<class 'numpy.float64'>'    with 10 stored elements in COOrdinate format>

然而,如果你调用toarray,你会得到一个更容易处理或至少更容易理解的结果:

>>> onehotencoder.fit_transform(df[0].values.reshape(1,-1)).toarray()array([[1., 2., 2., 1., 1., 2., 2., 1., 1., 1.]])

另一种方法是在创建OneHotEncoder时使用sparse = False,这样它默认会创建一个密集数组:

onehotencoder = OneHotEncoder(categorical_features= [0], sparse=False)>>> onehotencoder.fit_transform(df[0].values.reshape(1,-1))array([[1., 2., 2., 1., 1., 2., 2., 1., 1., 1.]])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注