【问题标题】:Keras GRU/LSTM layer input dimension errorKeras GRU/LSTM 层输入维度错误
【发布时间】:2019-01-21 03:26:21
【问题描述】:

我是深度学习的新手,我一直在尝试使用深度学习方法进行自然语言处理并使用路透社数据集创建一个简单的情感分析器。这是我的代码:

import numpy as np
from keras.datasets import reuters
from keras.preprocessing.text import Tokenizer
from keras.models import Sequential
from keras.layers import Dense, Dropout, GRU
from keras.utils import np_utils
max_length=3000
vocab_size=100000
epochs=10
batch_size=32
validation_split=0.2
(x_train, y_train), (x_test, y_test) = reuters.load_data(path="reuters.npz",
                                                         num_words=vocab_size,
                                                         skip_top=5,
                                                         maxlen=None,
                                                         test_split=0.2,
                                                         seed=113,
                                                         start_char=1,
                                                         oov_char=2,
                                                         index_from=3)

tokenizer = Tokenizer(num_words=max_length)

x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')
y_train = np_utils.to_categorical(y_train, 50)
y_test = np_utils.to_categorical(y_test, 50)


model = Sequential()
model.add(GRU(50, input_shape = (49,1), return_sequences = True))
model.add(Dropout(0.2))
model.add(Dense(256, input_shape=(max_length,), activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(50, activation='softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
model.summary()

history = model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=validation_split)

score = model.evaluate(x_test, y_test)
print('Test Accuracy:', round(score[1]*100,2))

我不明白为什么,每次我尝试使用 GRU 或 LSTM 单元而不是 Dense 单元时,都会收到此错误:

ValueError:检查输入时出错:预期 gru_1_input 有 3 尺寸,但得到了形状为 (8982, 3000) 的数组

我在网上看到添加return_sequences = True 可以解决问题,但正如您所见,问题仍然存在于我的情况。

在这种情况下我该怎么办?

【问题讨论】:

  • 你的x_train.shape 是(8982, 3000) - input_shape = (49,1) 来自哪里?

标签: python keras nlp deep-learning lstm


【解决方案1】:

问题在于x_train 的形状是(8982, 3000),所以这意味着(考虑到预处理阶段)有 8982 个句子被编码为单热向量,词汇大小为 3000。另一方面,一个 GRU (或 LSTM)层接受序列作为输入,因此其输入形状应为(batch_size, num_timesteps or sequence_length, feature_size)。目前,您拥有的特征是句子中特定单词的存在 (1) 或不存在 (0)。因此,要使其与 GRU 一起使用,您需要向 x_train 和 x_test 添加第三个维度:

x_train = np.expand_dims(x_train, axis=-1)
x_test = np.expand_dims(x_test, axis=-1)

然后删除 return_sequences=True 并将 GRU 的输入形状更改为 input_shape=(3000,1)。这样,您就告诉 GRU 层您正在处理长度为 3000 的序列,其中每个元素都由一个特征组成。 (作为旁注,我认为您应该将vocab_size 传递给Tokenizer 的num_words 参数。这表示词汇表中的单词数。相反,将max_length 传递给load_data 的maxlen 参数,这限制了一个句子的长度。)

但是,我认为如果您使用Embedding layer 作为第一层并且在 GRU 层之前,您可能会得到更好的结果。那是因为目前你编码句子的方式没有考虑句子中单词的顺序(它只关心它们的存在)。因此,用这种表示形式提供依赖于序列中元素顺序的 GRU 或 LSTM 层是没有意义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 2022-01-20
    • 2023-03-05
    相关资源
    最近更新 更多