【问题标题】:Input shape for Keras LSTM/GRU language modelKeras LSTM/GRU 语言模型的输入形状
【发布时间】:2016-11-09 12:23:11
【问题描述】:

我正在尝试在 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 个维度。我不知道第三维应该是什么。

【问题讨论】:

    标签: python nlp keras lstm language-model


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2021-11-19
      相关资源
      最近更新 更多