gpt4 book ai didi

tensorflow - 与 keras 进行注意卷积

转载 作者:行者123 更新时间:2023-11-30 09:07:24 25 4
gpt4 key购买 nike

我已经在 keras 中实现了一个注意力卷积层,如本文 paper 中所述。 .

您可以在此处查看它的代码 gist

我是实现自定义层的新手,但它仍然很慢。我使用了很多 tf.map_fn ,我认为这就是它如此慢的原因,但我不知道有什么不同的方法来做到这一点。如果有人有一些如何改进层的技巧或关于实现自定义层的一般技巧(例如如何避免后端( tensorflow )函数),那就太好了。

我使用 keras 2.1.3 和 tensorflow 1.5 作为后端。

谢谢

最佳答案

我不明白你为什么使用tf.map_fn,你可以在任何地方避免它......

这里有一些提示(可能会也可能不会使代码更快)。

选角

您真的需要将值转换为 float 值吗?如果(至少)x[0] 是一个嵌入,那么它就已经是一个 float 了,对吧? (不确定“上下文”的本质)

第 37 行和第 38 行:

text = x[0]
context = x[1]

为什么要使用 keras 中已经支持的映射函数?

例如,为什么要这样做(L42):

weighted_attentive_context = tf.map_fn(self._compute_attentive_context, (text, context), dtype=K.floatx())

什么时候可以做到这一点?

weighted_attentive_context = self._compute_attentive_context(text,context)

与:

def _comput_attentive_context(self,text,context):

_compute_attentive_context的建议:

def _compute_attentive_context(self, text, context):

#computes the context-score for every vector like equation 2
temp = tf.matmul(text, self.We)
scores = tf.matmul(temp, K.transpose(context))

#why not?
scores_softmax = K.softmax(scores)


#computes the context featur_map like equation 4
res = tf.matmul(scores_softmax, context)

#why not?
res = self._weight_for_output(res)
return res

为什么不使用 K.conv1D 来代替所有这些复杂的重复、串联等?

def _conv(self, x):
return K.conv1D(x, self.W1, padding='same')

#if you have special reasons for what you're doing, please share them in the comments,
#please also share the exact shapes of the inputs and desired outputs
#here, you should make self.W1 with shape (filterLength, em_dim, desired_output_dim)

通话建议:

def call(self, x, mask=None):
#x is a list of two tensors
text = x[0]
context = x[1]

#applies bilinear energy funtion (text * We * context)
#and weights the computed feature map like in equation 6 (W2 * ci)
weighted_attentive_context = self._compute_attentive_context(text, context)

#does the actual convolution, this is still kind of hacky
conv = K.conv1D(text,self.W1,padding='same')

added = conv + weighted_attentive_context
batch = K.bias_add(added, self.bias)
return batch

批量矩阵乘法

对于这些乘法,您可以使用 K.dot(),如下所示:

  • 如果批处理 x 权重:K.dot(x, self.W)
  • 如果权重为 x 批处理:K.permute_dimensions(K.dot(self.W,x),(1,0,2))

考虑到你有这些形状:

  • 如果批处理 x 权重 -> x: (批处理, 单词, emb) | W:(emb,任意)
  • 如果权重 x 批处理 -> W:(任意,单词)| x:(批处理、单词、emb)

结果将是:

  • 如果批处理 x 权重:(字数,任意)<- 这似乎是合乎逻辑的选择
  • 如果重量为 x 批处理:(任意,emb)

关于tensorflow - 与 keras 进行注意卷积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48621769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com