【问题标题】:Keras - LSTM with embeddings of 2 words at each time stepKeras - 每个时间步嵌入 2 个单词的 LSTM
【发布时间】:2018-08-31 12:31:07
【问题描述】:

下面的代码构建了一个 LSTM 模型。 我想将这个确切的模型更改为在开始时有一个嵌入层,它在每个时间步接收 2 个不同的单词,嵌入它们(使用相同的嵌入层):它连接它们的嵌入,然后遵循我的模型的其余部分.

k_model = Sequential()

k_model.add(LSTM(int(document_max_num_words*1.5), input_shape=(document_max_num_words, num_features)))
k_model.add(Dropout(0.3))
k_model.add(Dense(num_categories))
k_model.add(Activation('sigmoid'))

k_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

【问题讨论】:

  • 所以训练数据的形状应该是(n_smaples, n_timesteps, 2),对吧?

标签: python keras concatenation lstm embedding


【解决方案1】:

如果我正确理解您的问题,假设输入数据的形状为 (n_samples, n_timesteps, 2)(即每步两个字),您可以使用 TimeDistributed 包装器实现您想要的:

from keras import layers
from keras import models

n_vocab = 1000
n_timesteps = 500
embed_dim = 128
words_per_step = 2

model = models.Sequential()
model.add(layers.TimeDistributed(layers.Embedding(n_vocab, embed_dim), input_shape=(n_timesteps, words_per_step)))
model.add(layers.TimeDistributed(layers.Flatten()))
# the rest of the model

model.summary()

模型总结:

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
time_distributed_12 (TimeDis (None, 500, 2, 128)       128000    
_________________________________________________________________
time_distributed_13 (TimeDis (None, 500, 256)          0         
=================================================================
Total params: 128,000
Trainable params: 128,000
Non-trainable params: 0
_________________________________________________________________

【讨论】:

  • 谢谢,我去看看。这个模型的输入是什么?单词的顺序?我的意思是-这是否准备了单热编码? n_vocab 应该说明数据中的单词数?
  • @Codevan 输入的是单词的索引(即两个单词对应的两个整数)。对于每个单词,您需要考虑一个唯一的整数索引。嵌入层只是一个可训练的查找表:它获取单词的索引并为您提供相应的单词向量。 n_vocab 是词汇表中唯一单词的总数。
  • 你知道我可以有效地将这对单词转化为索引吗?
  • @Codevan 你可以使用Keras Tokenizer
猜你喜欢
  • 2017-07-26
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
相关资源
最近更新 更多