独热编码增加了目标数据的尺寸

我有多类别数据,标签或y列包含以下数据:

print(y.unique())

[5 6 7 4 8 3 9]在这种情况下,类别的数量等于7(在深度学习建模时),但当我执行以下独热编码时:

import kerasfrom keras.utils import np_utilsy_train =np_utils.to_categorical(y_train)y_test =np_utils.to_categorical(y_test)

维度增加到了10

print(y_train.shape) : (4547, 10)

可能是因为我们有到9的数字,并且还包括了(0,1,2)(实际上在原始数据中并未表示),我该如何解决这个问题?


回答:

函数 tf.keras.utils.to_categorical 要求输入是“从0到num_classes的整数”(见文档)。您有一组标签 {3, 4, 5, 6, 7, 8, 9}。这总共有七个标签,从值3开始。为了将这些标签转换为[0, 7)范围内的标签,可以从每个标签中减去3。

y_ints = y - 3

结果可以传递给 tf.keras.utils.to_categorical

import numpy as npimport tensorflow as tfy = np.array([3, 4, 5, 6, 7, 8, 9])y_ints = y - 3  # [0, 1, 2, 3, 4, 5, 6]tf.keras.utils.to_categorical(y_ints)

输出为

array([[1., 0., 0., 0., 0., 0., 0.],       [0., 1., 0., 0., 0., 0., 0.],       [0., 0., 1., 0., 0., 0., 0.],       [0., 0., 0., 1., 0., 0., 0.],       [0., 0., 0., 0., 1., 0., 0.],       [0., 0., 0., 0., 0., 1., 0.],       [0., 0., 0., 0., 0., 0., 1.]], dtype=float32)

另一种选择是使用scikit-learn的广泛预处理方法,特别是sklearn.preprocessing.OneHotEncoder

import numpy as npfrom sklearn.preprocessing import OneHotEncodery = np.array([3, 4, 5, 6, 7, 8, 9])y = y.reshape(-1, 1)  # reshape to (n_samples, n_labels).encoder = OneHotEncoder(sparse=False, dtype="float32")encoder.fit_transform(y)

输出为

array([[1., 0., 0., 0., 0., 0., 0.],       [0., 1., 0., 0., 0., 0., 0.],       [0., 0., 1., 0., 0., 0., 0.],       [0., 0., 0., 1., 0., 0., 0.],       [0., 0., 0., 0., 1., 0., 0.],       [0., 0., 0., 0., 0., 1., 0.],       [0., 0., 0., 0., 0., 0., 1.]], dtype=float32)

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中创建了一个多类分类项目。该项目可以对…

发表回复

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