【问题标题】:Classify a sequence using LSTM in keras在 keras 中使用 LSTM 对序列进行分类
【发布时间】:2017-11-16 20:21:02
【问题描述】:

我正在研究一个二元分类问题,其中网络接受两个输入并输出这个输入对的标签。

基本上,我首先使用编码器层进行嵌入并将嵌入结果连接起来。接下来,我将使用 RNN 结构对级联结果进行分类。但是我想不出编写代码的正确方法。我在下面附上我的代码。

input_size = n_feature # the number of features
encoder_size = 2000 # output dim for each encoder
dropout_rate = 0.5 
X1 = Input(shape=(input_size, ), name='input_1')
X2 = Input(shape=(input_size, ), name='input_2')

encoder = Sequential()
encoder.add(Dropout(dropout_rate, input_shape=(input_size, )))
encoder.add(Dense(encoder_size, activation='relu'))

encoded_1 = encoder(X1)
encoded_2 = encoder(X2)
merged = concatenate([encoded_1, encoded_2])

#----------Need Help---------------#
comparer = Sequential()
comparer.add(LSTM(512, input_shape=(encoder_size*2, ), return_sequences=True))
comparer.add(Dropout(dropout_rate))
comparer.add(TimeDistributed(Dense(1)))
comparer.add(Activation('sigmoid'))
#----------Need Help---------------#

Y = comparer(merged)
model = Model(inputs=[X1, X2], outputs=Y)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

似乎对于 LSTM 层,输入应该是(None, encoder_size*2)。我尝试使用Y = comparer(K.transpose(merged)) 重塑 LSTM 层的输入,但失败了。顺便说一句,对于这个网络,输入形状是(input_size,),输出形状是(1,)。

【问题讨论】:

  • 您希望编码器输出什么?单个向量还是向量序列?
  • 只是一个向量。对于 LSTM,我希望看到它可以将此向量视为时间序列,这样它就可以记住之前看到的值。
  • 您需要使用stateful 选项和reshape 使其具有三维效果。
  • 你能给我一个演示吗?我是 RNN 和 keras 的初学者。另外,如果我们这样做,恐怕输出层将是 (None, 1,1) ,这不是我想要的。

标签: keras


【解决方案1】:

如果想法是按时间序列转换输入向量,您可以简单地对其进行重塑:

comparer = Sequential()

#reshape the vector into a time series form: (None, timeSteps, features)
comparer.add(Reshape((2 * encoder_size,1), input_shape=(2*encoder_size,))

#don't return sequences, you don't want a sequence as result:
comparer.add(LSTM(512, return_sequences=False))

comparer.add(Dropout(dropout_rate))

#Don't use a TimeDistributed, you're not dealing with a series anymore  
comparer.add(Dense(1))

comparer.add(Activation('sigmoid'))

【讨论】:

  • 它有效,但我收到了一条温暖的消息2017-11-16 09:48:46.605652: I tensorflow/core/common_runtime/gpu/pool_allocator.cc:247] PoolAllocator: After 14091 get requests, put_count=24107 evicted_count=10000 eviction_rate=0.414817 and unsatisfied allocation rate=0,即使我设置了batch_size=1。正常吗?
  • 听起来很奇怪。我不明白那个错误。更改批量大小会改变这些计数吗?
  • 实际上,当batch size太大时,我遇到了另一个问题。之前的设置是RNN层的输入形状是(2000*2,1)和batch_size=200,那么我们就有内存错误。我将编码器大小减小到 500 并将批量大小减小到 20 以避免此类错误。批量大小是否需要批量处理 RNN 中的单元格数量?我上面贴的警告信息在前几批出现,然后就消失了。
  • 不,RNN 中的单元数/单元数与批量大小无关。但我不知道那个警告信息是什么意思。我以前从未见过。
猜你喜欢
  • 2021-01-25
  • 2019-06-24
  • 2021-10-20
  • 2020-02-08
  • 2018-11-25
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
相关资源
最近更新 更多