【问题标题】:Keras expected embedding_13_input to have 2 dimensions, but got array with shape (20, 7, 12)Keras 期望 embedding_13_input 有 2 维,但是得到了形状为 (20, 7, 12) 的数组
【发布时间】:2021-03-04 21:32:20
【问题描述】:

我知道这个问题已经被问过很多次了,但是我无法使用 SO 的任何答案来解决这个错误。我正在尝试构建嵌入,我的数据被塑造成:(20, 7, 12) 即 20 个训练样本,每个有 7 个单词,one-hot 编码为 12 维。

当我使用以下规格拟合我的模型时,我收到错误:

检查输入时出错:预期 embedding_24_input 有 2 尺寸,但得到形状为 (20, 7, 12) 的数组

embedding_dims = 10
model = Sequential()
model.add(Embedding(12, embedding_dims,input_length=7))

然后我尝试在嵌入之前展平,但未能成功抱怨“input_length”为 7,但接收到的输入具有形状(无,84)“。然后我更改了嵌入层上的 input_length 以匹配但没有运气要么:

检查目标时出错:预期 embedding_26 有 3 尺寸,但得到形状为 (20, 12) 的数组

model = Sequential()
model.add(Flatten())
model.add(Embedding(12, embedding_dims,input_length=84))

非常感谢您提供任何解释帮助!

【问题讨论】:

    标签: python keras


    【解决方案1】:

    Embedding 层不要期望输入数据中的一种热编码,您应该使用 numpy.argmaxtf.argmax 等函数将数据转换为整数Embedding 层中馈送数据之前的大小矩阵(batch,input_length)。

    下面的例子没有任何错误:

    import tensorflow as tf
    import numpy as np
    
    embedding_dims = 10
    batch_size = 20
    vocabulary_size = 12
    
    # The model will take as input an integer matrix of size (batch, input_length), 
    # and the largest integer (i.e. word index) in the input should be no larger than 11 (vocabulary size - 1)
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Embedding(vocabulary_size, embedding_dims, input_length=7))
    model.compile('rmsprop', 'mse')
    
    raw_input_array = np.random.randint(2, size=(batch_size, 7, vocabulary_size))
    input_array = np.argmax(raw_input_array, axis=-1)
    output_array = model.predict(input_array)
    print("One hot encodeing data shape: {}\ninput integer matrix shape: {}\noutput shape: {}\n".format(raw_input_array.shape, input_array.shape, output_array.shape))
    

    输出:

    One hot encodeing data shape: (20, 7, 12)
    input integer matrix shape: (20, 7)
    output shape: (20, 7, 10)
    

    【讨论】:

    • 抱歉,我需要考虑一下这个问题。 1. Embedding Layer的重点不就是将稀疏的one-hot向量转换为稠密的向量吗? 2.既然argmax是把onehot转成index,那这不是违背定量规律吗?即如果两个不相关的标记在附近(按索引),那么模型错误地假设它们是相关的?
    • 我想你想多了,查看tf.keras.layers.Embedding 的第一行文档,它的作用是:将正整数(索引)转换为固定大小的密集向量。即 Embedding 层是向量查找表的索引,理论上我们可以使用 one-hot 向量来检索向量,但是 tensorflow 出于效率考虑使用索引,在 Embedding 层之后的所有层都不会直接看到索引,而只会看到由检索到的任何向量查找表中的索引,因此无需担心该法律
    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2020-06-18
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多