【问题标题】:Dimensionality Error when using Bidirectional LSTM with an embedding layer, on multi-label classification在多标签分类中使用带有嵌入层的双向 LSTM 时出现维度错误
【发布时间】:2019-01-13 21:11:42
【问题描述】:

我试图使用双向 LSTM 将文本数据(句子)分类到某些类。我以其中 3 个为例。我遵循multilabel-classification-post,即“使用 sigmoid 激活输出层”、“使用 binary_crossentropy 进行损失函数”。我使用了一个嵌入层(大小为 300 的词向量)。我的句子被填充和截断,因此每个句子都有 100 个标记。这是我的模型的代码:

model = Sequential()

embedding_layer = Embedding(6695,
                        300,
                        weights=[embedding_matrix],

                    input_length=100,
                        trainable=True)

model.add(embedding_layer)
model.add(Bidirectional(LSTM(32, 
          return_sequences=False)))
model.add(Dense(3, 
          activation='sigmoid'))

model.compile(loss='binary_crossentropy',
          optimizer='rmsprop',
          metrics=['acc'])

print("model fitting - Bidirectional LSTM")
model.summary()

x= model.fit(X_train, y_train,
            batch_size=256,
            epochs=6,
            validation_data=(X_val, y_val),
            shuffle = True,
            verbose = 1
      )

这是模型摘要,这是预期的: enter image description here

但是,我得到了这个错误:

Traceback (most recent call last):
  File "/Users/master/Documents/Deep Learning/Learning Keras/reveiw_classification.py", line 159, in <module>
    verbose = 1
  File "/Users/master/.pyenv/versions/ENV4/lib/python3.6/site-packages/keras/engine/training.py", line 955, in fit
    batch_size=batch_size)
  File "/Users/master/.pyenv/versions/ENV4/lib/python3.6/site-packages/keras/engine/training.py", line 792, in _standardize_user_data
    exception_prefix='target')
  File "/Users/master/.pyenv/versions/ENV4/lib/python3.6/site-packages/keras/engine/training_utils.py", line 136, in standardize_input_data
    str(data_shape))
ValueError: Error when checking target: expected dense_1 to have shape (3,) but got array with shape (100,)

我不需要 LSTM 返回一系列隐藏状态输出,我只需要最后一个输出。我以为我在 LSTM 中使用了 return_sequences=False,因此输出的维度应该是 1,然后一个具有 32 个单位的双向 LSTM 将具有模型摘要中的输出维度 (None,64)。但是为什么它说期望dense_1具有形状(3,)但得到形状为(100,)的数组?有人可以帮我吗?

【问题讨论】:

    标签: python keras lstm bidirectional multilabel-classification


    【解决方案1】:

    看起来你的目标 y_train 实际上是句子而不是标签向量 [1, 0, 1] 例如。错误与模型无关,而是与您传递的数据有关。

    • 您的 y_train 应该是形状为 (num_samples, 3) 的二维数组,因此对于每个样本(句子),您都有一个包含 3 个标签的向量目标
    • 在这种情况下,X_train 类似于 (num_samples, 100),即输入长度为 100 的句子。

    【讨论】:

    • 我确实把 y 变成了标签向量。但是,我填充到 100 的长度,这导致了问题
    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 2019-01-21
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多