Keras GRU / LSTM层输入尺寸误差

问题描述 投票:1回答:1

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

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单元而不是密集单元时,我都会收到此错误:

ValueError:检查输入时出错:预期gru_1_input有3个维度,但得到的数组有形状(8982,3000)

我在网上看到添加return_sequences = True可以解决问题,但正如你所看到的,问题仍然存在于我的案例中。

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

python keras nlp deep-learning lstm
1个回答
1
投票

问题是x_train的形状是(8982, 3000)所以它意味着(考虑到预处理阶段)有8982个句子被编码为一个热词矢量,词汇大小为3000.另一方面,GRU(或LSTM)层接受一个序列作为输入,因此它的输入形状应该是(batch_size, num_timesteps or sequence_length, feature_size)。目前,您拥有的功能是句子中特定单词的存在(1)或不存在(0)。因此,要使其与GRU一起使用,您需要为x_trainx_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传递给num_wordsTokenizer论证。这表明词汇中的单词数量。相反,将max_length传递给maxlen load_data论证,这限制了句子的长度。)

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

© www.soinside.com 2019 - 2024. All rights reserved.