【问题标题】:Keras ValueError: input 0 is incompatible with layer flatten_11Keras ValueError:输入 0 与 flatten_11 层不兼容
【发布时间】:2018-07-24 10:53:26
【问题描述】:

尝试按照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,)

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

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

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

    实际的错误是抱怨虽然目标是 (3,) 这是您的标签,但您的最终密集层输出 33 个值。所以它看起来像 len(labels_index) == 33 而不是你数据中的 3。

    【讨论】:

    • 将标签创建更改为:for text in texts: label_id = len(labels_index) labels_index[text] = label_id labels.append(label_id) 但现在它反馈数组的形状为 34。越来越近,但知道我需要更改什么来修复它吗?
    • 这听起来是特定的数据,所以我很难说。至少你知道问题出在哪里,你的标签数量与模型基本不符。
    猜你喜欢
    • 1970-01-01
    • 2017-11-06
    • 2021-07-04
    • 2020-11-28
    • 2021-05-31
    • 2021-09-13
    • 1970-01-01
    • 2022-07-22
    相关资源
    最近更新 更多