【问题标题】:Using custom tensorflow ops in keras在 keras 中使用自定义张量流操作
【发布时间】:2018-08-01 16:20:21
【问题描述】:

我在 tensorflow 中有一个包含自定义 tensorflow 操作的脚本。我想将代码移植到 keras,但不知道如何在 keras 代码中调用自定义操作。

我想在 keras 中使用 tensorflow,所以到目前为止我发现的教程描述的与我想要的相反:https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html

我还阅读了有关可以包装任意自定义函数的 Lambda 层,但我没有看到 tf.ops 的示例。

如果您能提供代码 sn-p 以及如何做到这一点的最简单示例,我将不胜感激。例如假设 tf.ops 为:

outC = my_custom_op(inA, inB)

---编辑: here 中已经描述了类似的问题 - 本质上是在 keras 中调用 this 自定义操作,但是我无法掌握如何将其应用于我想要的另一个示例的解决方案,例如 this 一个。这个自定义的 tf op 首先被编译(用于 gpu),然后在 tensorflow 中作为here 使用,见@ 第 40 行。我很清楚如何使用包装在 Lambda 层中的自定义(lambda)函数,我会想了解的是如何使用编译的自定义操作,如果我使用 keras。

【问题讨论】:

  • 你的意思是自定义层吗?
  • 为了在 Keras 中使用 TensorFlow,您可以使用from keras import backend as K,其中K 对应于 TensrFlow。例如K.nn.relu 等价于tf.nn.relu
  • @Colonder,感谢您的帮助。请阅读更新的说明。我不确定这个预编译的自定义操作是否可以/应该成为自定义层。如果是的话,这就是我想通过一个简单的例子来理解的概念,我在上面提供了示例性的 github repos。

标签: python tensorflow keras


【解决方案1】:

您可以将任意 tensorflow 函数包装在 keras Lambda 层中,并将它们添加到您的模型中。最小的工作示例from this answer:

import tensorflow as tf
from keras.layers import Dense, Lambda, Input
from keras.models import Model

W = tf.random_normal(shape=(128,20))
b = tf.random_normal(shape=(20,))

inp = Input(shape=(10,))
x = Dense(128)(inp)
# Custom linear transformation
y = Lambda(lambda x: tf.matmul(x, W) + b, name='custom_layer')(x) 
model = Model(inp, y)

【讨论】:

  • 我认为坚持 Keras 的意识形态并做 from keras import backend as K 而不是 import tensorflow as tf 会更好
  • keras 后端是否提供所有 tensorflow 函数?例如,K.matmul 给了我一个错误。
  • 是的,但它们的名称不同。 tf.matmul 等价于 K.dot
  • 但是,归根结底,这并不重要
  • 不,所有的 tensorflow 函数在 keras 后端都不可用。而且很多都发生了变化,使用不同的输入,功能有限。我尝试了一段时间只使用 K 函数,但这太局限了。 -- 使用tf 而不是K 的唯一问题是失去将代码迁移到其他后端的可能性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 2021-02-08
  • 2020-05-30
  • 2019-02-23
相关资源
最近更新 更多