machine-learning - 如何使用 to_categorical 将 [[4,7,10],[10,20,30]] 转换为一种热编码

标签 machine-learning keras deep-learning

我正在研究 LSTM。

输出是分类的。

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

我能够对一维数组做到这一点,但我发现对二维数组做到这一点很困难。

from keras.utils import to_categorical
print(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.shape
totalFeatures = myData.max() + 1

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

关于machine-learning - 如何使用 to_categorical 将 [[4,7,10],[10,20,30]] 转换为一种热编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51271145/

相关文章:

python - Keras 模型为多标签图像分类提供非常低的训练和验证精度

python - 如何在 Keras 中强制执行(回归)模型输出的单调性?

python - Keras/Tensorflow CNN 输入形状

python - Receiving Assertion failed While generate adversarial samples 通过任何方法

python - ELMo 嵌入层与 Keras

tensorflow - 使用BERT预测下一句

python - 在 H2O 中校准 AutoML 模型

machine-learning - 通过查找事件来总结文本文档(多文档,即新闻)

python - Tensorflow 抛出 "TypeError: unhashable type: ' list'"错误

Tensorflow 服务在基本路径下找不到可服务的 <MODEL> 版本