【发布时间】:2018-09-30 05:03:35
【问题描述】:
我在deep Deep Learning with Python的第7章第1节找到一段代码如下:
from keras.models import Model
from keras import layers
from keras import Input
text_vocabulary_size = 10000
question_vocabulary_size = 10000
answer_vocabulary_size = 500
# Our text input is a variable-length sequence of integers.
# Note that we can optionally name our inputs!
text_input = Input(shape=(None,), dtype='int32', name='text')
# Which we embed into a sequence of vectors of size 64
embedded_text = layers.Embedding(64, text_vocabulary_size)(text_input)
# Which we encoded in a single vector via a LSTM
encoded_text = layers.LSTM(32)(embedded_text)
# Same process (with different layer instances) for the question
question_input = Input(shape=(None,), dtype='int32', name='question')
embedded_question = layers.Embedding(32, question_vocabulary_size)(question_input)
encoded_question = layers.LSTM(16)(embedded_question)
# We then concatenate the encoded question and encoded text
concatenated = layers.concatenate([encoded_text, encoded_question], axis=-1)
# And we add a softmax classifier on top
answer = layers.Dense(answer_vocabulary_size, activation='softmax')(concatenated)
# At model instantiation, we specify the two inputs and the output:
model = Model([text_input, question_input], answer)
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['acc'])
你看到这个模型的输入没有原始数据的形状信息,那么在Embedding层之后,LSTM的输入或者Embedding的输出都是一些可变长度的序列。
所以我想知道:
- 在这个模型中,keras如何确定LSTM层中lstm_unit的个数
- 如何处理变长序列
附加信息:为了解释lstm_unit是什么(我不知道如何调用它,所以只是显示它的图像):
【问题讨论】:
-
看看这个,要创建一个固定的序列长度,有一个实用函数keras.io/preprocessing/sequence/#pad_sequences
-
由于这不符合独立答案的条件,因此我将发表评论。除了@Daniel 和@ely 在他们的答案中引用的零填充、1 大小的批次和大小聚类之外,还有另一种很少使用但非常强大的方法来处理可变长度的输入。它被称为有状态学习(您可能已经注意到 Keras 的 RNN 层中的
stateful选项)。正确使用很棘手,但绝对值得了解。
标签: python machine-learning deep-learning keras lstm