Keras LSTM / GRU语言模型的输入形状

ish*_*ido 2 python nlp language-model lstm keras

我正在尝试在Keras中训练单词级别的语言模型。

我的X和Y的形状均为(90582L,517L)

当我尝试拟合此模型时:

print('Build model...')
model = Sequential()
model.add(GRU(512, return_sequences=True, input_shape=(90582, 517)))
model.add(Dropout(0.2))
model.add(GRU(512, return_sequences=True))
model.add(Dropout(0.2))
model.add(TimeDistributedDense(1))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.fit(x_pad, y_pad, batch_size=128, nb_epoch=2)
Run Code Online (Sandbox Code Playgroud)

我得到错误:

Exception: Error when checking model input: 
expected gru_input_7 to have 3 dimensions, but got array with shape (90582L, 517L)
Run Code Online (Sandbox Code Playgroud)

我需要一些有关输入形状应该如何的指导?我已经对各种组合进行了反复试验,但似乎我误解了一些基本知识。

在Keras文本生成示例中,X矩阵具有3个维度。我不知道第三维应该是什么。

Lor*_*rit 5

这取决于您要执行的操作。我想您的形状数据(90582,517)是一组90582个样本,每个样本有517个单词。如果是这样,则必须将您的单词转换为单词向量(=嵌入),以使其有意义。然后,您将具有可以由GRU处理的形状(90582,517,embedding_dim)。

Keras嵌入层可以为你做的。将其添加为第一个GRU层之前的神经网络的第一层。

vocabulary_size = XXXXX     # give your vocabulary size here (largest word ID in the input)
embedding_dim = XXXX        # give your embedding dimension here (e.g. 100)

print('Build model...')
model = Sequential()
model.add(Embedding(vocabulary_size, embedding_dim, input_shape=(90582, 517)))
model.add(GRU(512, return_sequences=True))
model.add(Dropout(0.2))
model.add(GRU(512, return_sequences=True))
model.add(Dropout(0.2))
model.add(TimeDistributedDense(1))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.fit(x_pad, y_pad, batch_size=128, nb_epoch=2)
Run Code Online (Sandbox Code Playgroud)