【问题标题】:Keras - Wrong input shape in LSTM dense layerKeras - LSTM 密集层中的错误输入形状
【发布时间】:2019-02-18 11:17:21
【问题描述】:

我正在尝试使用Keras 构建一个lstm 文本分类器。

这是模型结构:

model_word2vec = Sequential()
model_word2vec.add(Embedding(input_dim=vocabulary_dimension,
                    output_dim=embedding_dim,
                    weights=[word2vec_weights,
                    input_length=longest_sentence,
                    mask_zero=True,
                    trainable=False))
model_word2vec.add(LSTM(units=embedding_dim, dropout=0.25, recurrent_dropout=0.25, return_sequences=True))
model_word2vec.add(Dense(3, activation='softmax'))
model_word2vec.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])


results = model_word2vec.fit(X_tr_word2vec, y_tr_word2vec, validation_split=0.16, epochs=3, batch_size=128, verbose=0)

其中y_tr_word2vec 是一个3 维one-hot 编码变量。

当我运行上面的代码时,我得到了这个错误:

ValueError: Error when checking model target: expected dense_2 to have 3 dimensions, but got array with shape (15663, 3)

我认为问题可能与y_tr_word2vec 形状或batch size 尺寸有关,但我不确定。

更新:

我已将密集层中的return_sequences=Falsey_tr_word2vecone-hot 更改为categorical1 神经元,现在我使用sparse_categorical_crossentropy 而不是categorical_crossentropy

现在,我收到此错误:ValueError: invalid literal for int() with base 10: 'countess'

因此,现在我假设在fit() 期间,包含句子的输入向量X_tr_word2vec 出现问题。

【问题讨论】:

  • 您尝试过 keras.utils.to_categorical(y_tr_word2vec, num_classes=3) 吗?您对模型的输入似乎不正确。
  • 您的模型中的神经元数量是由我们看不到的变量分配的,请发布它们。我的意思是vocabulary_dimensionembedding_dim,如果还有其他的话。还有dim_embeddingembedding_dim 是两个不同的东西,这是故意的吗?
  • @DanielR。这些是同一个变量,我已经更新了测试。
  • @AmirHadifar 我已经尝试过了,正如我在更新中所写的那样。现在,我收到此错误:ValueError: invalid literal for int() with base 10: 'countess'.

标签: python keras lstm text-classification


【解决方案1】:

问题是这段代码

model_word2vec.add(LSTM(units=dim_embedding, dropout=0.25, recurrent_dropout=0.25, return_sequences=True))
model_word2vec.add(Dense(3, activation='softmax'))

你设置了return_sequences=True,这意味着LSTM会返回一个3D数组到dense layer,而dense不需要3D数据...所以删除return_sequences=True

model_word2vec.add(LSTM(units=dim_embedding, dropout=0.25, recurrent_dropout=0.25))
model_word2vec.add(Dense(3, activation='softmax'))

为什么要设置 return_sequences=True?

【讨论】:

  • 我试过了,但现在我得到了'[12406 9070 6608 9899 7373 5589 ......] are not in index
猜你喜欢
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 2020-08-17
  • 2017-07-08
相关资源
最近更新 更多