如何使用to_categorical将[[4,7,10],[10,20,30]]转换为独热编码

我正在研究LSTM模型。

输出是分类数据。

其格式为[[t11,t12,t13],[t21,t22,t23]]

我能够在一维数组上实现,但对于二维数组我发现有些困难。

from keras.utils import to_categoricalprint(to_categorical([[9,10,11],[10,11,12]]))

输出

[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]]

有两个不同的输入,每个输入有3个时间步,但在输出中它们都被合并了。

我需要的输出是,

[[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.]],[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.][ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]]]

回答:

如果形状很奇怪,可以尝试将其变成一维,使用函数,然后再重塑回原来的形状:

originalShape = myData.shapetotalFeatures = myData.max() + 1categorical = myData.reshape((-1,))categorical = to_categorical(categorical)categorical = categorical.reshape(originalShape + (totalFeatures,))

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

发表回复

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