在Keras中使用自定义Tensorflow Ops [英] Using custom tensorflow ops in keras
问题描述
我在tensorflow中有一个脚本,其中包含自定义tensorflow ops.我想将代码移植到keras,但不确定如何在keras代码中调用自定义操作.
I am having a script in tensorflow which contains the custom tensorflow ops. I want to port the code to keras and I am not sure how to call the custom ops within keras code.
我想在keras中使用tensorflow,所以到目前为止我发现的教程描述了与我想要的相反的内容:
I want to use tensorflow within keras, so the tutorial I found so far is describing the opposite to what I want: https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html.
我还阅读了有关可以包装任意自定义函数的Lambda层的信息,但我没有看到tf.ops的示例.
I also read about Lambda layers that can wrap arbitrary custom function, yet I did not see an example for tf.ops.
如果您能提供一个带有最简单示例的代码片段,我将非常感激.例如,假设tf.ops为:
If you could provide code snippet with a simplest example how to do that I would be very grateful. For example assuming the tf.ops as:
outC = my_custom_op(inA, inB)
--- 在此处中已描述了类似的问题-本质上是调用此一个.此自定义tf op首先进行编译(针对gpu),然后到目前为止在tensorflow中用作
--- Similar problem has been described in here - essentially calling this custom op in keras, however I cannot grasp the solution how to apply it on another example that I want, for instance this one. This custom tf op is first compiled (for gpu) and then so far used within tensorflow as here, see @ line 40. It is clear for me how to use a custom (lambda) function wrapped in Lambda layer, what I would like to understand is how to use the compiled custom ops, if I use keras.
推荐答案
您可以将任意张量流函数包装在keras Lambda
层中并将它们添加到模型中.最小的工作示例通过此答案:
You can wrap arbitrary tensorflow functions in a keras Lambda
layer and add them to your model. Minimal working example 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中使用自定义Tensorflow Ops的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!