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

时间:2016-07-07 08:48:01

标签: python nlp keras lstm language-model

我正在尝试在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)

我收到错误:

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

我需要一些关于输入形状应该是什么的指导?我已经对各种组合进行了反复试验,但似乎我误解了一些基本的东西。

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

1 个答案:

答案 0 :(得分:3)

这取决于你想要做什么。我猜您的形状数据(90582,517)是一组90582个样本,每个样本有517个单词。如果是这样,你必须将你的单词转换为单词向量(= embeddings),以使它们有意义。然后你将得到形状(90582,517,embedding_dim),它可以由GRU处理。

Keras Embedding layer可以为您做到这一点。在第一个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)