python - Keras 值错误 : input 0 is incompatible with layer flatten_11

标签 python tensorflow keras

尝试按照 https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html 上的教程进行操作为了使用预先存在的词嵌入来训练少量训练数据的模型。

我遇到的问题是当我尝试运行 1D Convnet 时,出现错误:

Input 0 is incompatible with layer flatten_11: expected min_ndim=3, found ndim=2

我的张量的维度是:

数据张量的形状:(91, 1000) 标签张量的形状:(91, 3)

问题出在这部分代码上:

sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
    embedded_sequences = embedding_layer(sequence_input)
    x = Conv1D(128, 5, activation='relu')(embedded_sequences)
    x = MaxPooling1D(5)(x)
    x = Conv1D(128, 5, activation='relu')(x)
    x = MaxPooling1D(5)(x)
    x = Conv1D(128, 5, activation='relu')(x)
    x = GlobalMaxPooling1D()(x)
    x = Flatten()(x)
    x = Dense(3, activation='relu')(x)
    preds = Dense(len(labels_index), activation='softmax')(x)

    model = Model(sequence_input, preds)
    model.compile(loss='categorical_crossentropy',
                  optimizer='rmsprop',
                  metrics=['acc'])

    model.fit(x_train, y_train,
               batch_size=128,
               epochs=10,
               validation_data=(x_val, y_val))

不进行扁平化,会反馈错误:

Error when checking target: expected dense_25 to have shape (33,) but got array with shape (3,)

我正在尝试找出需要更改的位置和内容,以确保尺寸正常工作,但是我还没有弄清楚我到底需要更改什么。任何帮助将不胜感激。

最佳答案

您应该关注没有 Flatten 的错误,因为您已经在使用 1D 卷积,因此不需要 Flatten 来传递到 Dense。

实际的错误是提示虽然目标是 (3,),即你的标签,但你的最终 Dense 层输出 33 个值。所以看起来像 len(labels_index) == 33 而不是数据中的 3。

关于python - Keras 值错误 : input 0 is incompatible with layer flatten_11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51496802/

相关文章:

tensorflow - `tf.image.decode_image`如何处理Tensorflow中的 channel ?

python - 模块未找到错误: No module named 'tensorflow'

python - AttributeError:模块 'tensorboard' 没有属性 'lazy'

python - LSTM RNN 同时预测多个时间步长和多个特征

python - 如何在 Python 中捕获对列表项的直接引用以提高速度?

python - PyInstaller 与 Pymongo 的问题

python - 如何从字典列表中删除重复值并保持原始顺序?

python - 将文件数据转换为嵌套列表

python - tensorflow - 无法将原型(prototype)文件构建到描述符池中

python - Keras 创建 CNN 模型 "The added layer must be an instance of class Layer"