【发布时间】:2018-03-08 14:30:46
【问题描述】:
我已经为 AttentiveLSTMCell 和 AttentiveLSTM(RNN) 编写了一个自定义 keras 层,符合 keras 对 RNN 的新方法。 Bahdanau 描述了这种注意机制,其中,在编码器/解码器模型中,从编码器的所有输出和解码器的当前隐藏状态创建“上下文”向量。然后,我在每个时间步将上下文向量附加到输入。
该模型用于制作对话代理,但在架构上与 NMT 模型非常相似(类似任务)。
但是,在添加这种注意力机制后,我的网络训练速度减慢了 5 倍,我真的很想知道如何以更高效的方式编写使网络速度减慢的部分代码方式。
这里的计算首当其冲:
h_tm1 = states[0] # previous memory state
c_tm1 = states[1] # previous carry state
# attention mechanism
# repeat the hidden state to the length of the sequence
_stm = K.repeat(h_tm1, self.annotation_timesteps)
# multiplty the weight matrix with the repeated (current) hidden state
_Wxstm = K.dot(_stm, self.kernel_w)
# calculate the attention probabilities
# self._uh is of shape (batch, timestep, self.units)
et = K.dot(activations.tanh(_Wxstm + self._uh), K.expand_dims(self.kernel_v))
at = K.exp(et)
at_sum = K.sum(at, axis=1)
at_sum_repeated = K.repeat(at_sum, self.annotation_timesteps)
at /= at_sum_repeated # vector of size (batchsize, timesteps, 1)
# calculate the context vector
context = K.squeeze(K.batch_dot(at, self.annotations, axes=1), axis=1)
# append the context vector to the inputs
inputs = K.concatenate([inputs, context])
在AttentiveLSTMCell 的call 方法中(一个时间步长)。
完整代码可以在here找到。如果有必要我提供一些数据和与模型交互的方法,那么我可以这样做。
有什么想法吗?当然,如果这里有什么聪明的地方,我会在 GPU 上进行训练。
【问题讨论】:
-
你能发布在一些样本训练时期使用
tensorflow.python.client.timeline.Timeline的输出吗?如果没有良好的分析器数据,基本上只是在黑暗中猜测原因。最好收集直接证据。 -
是的,我可以在一点点 @ely 上解决这个问题。
-
你分析过你的代码吗?猜测在哪里进行优化可能是一件愚蠢的事。我喜欢 Python line-profiler kernprof,并且你可以使用 Keras 的 TF 工具,比如 TensorBoard。
标签: python tensorflow keras vectorization