简体   繁体   English

具有高级计算功能的Keras自定义图层

[英]Keras Custom Layer with advanced calculations

I want to write some custom Keras Layers and do some advanced calculations in the layer, for example with Numpy, Scikit, OpenCV... 我想编写一些自定义Keras图层并在该图层中进行一些高级计算,例如使用Numpy,Scikit,OpenCV ...

I know there are some math functions in keras.backend that can operate on tensors, but i need some more advanced functions. 我知道keras.backend中有一些数学函数可以对张量进行运算,但是我需要一些更高级的函数。

However, i have no clue how to implement this correctly, i get the error message: 但是,我不知道如何正确执行此操作,我收到错误消息:
You must feed a value for placeholder tensor 'input_1' with dtype float and shape [...]

Here is my custom layer: 这是我的自定义层:

class MyCustomLayer(Layer):
    def __init__(self, **kwargs):
        super(MyCustomLayer, self).__init__(**kwargs)

    def call(self, inputs):
        """
        How to implement this correctly in Keras?
        """
        nparray = K.eval(inputs)  # <-- does not work
        # do some calculations here with nparray
        # for example with Numpy, Scipy, Scikit, OpenCV...
        result = K.variable(nparray, dtype='float32')
        return result

    def compute_output_shape(self, input_shape):
        output_shape = tuple([input_shape[0], 256, input_shape[3]])
        return output_shape  # (batch, 256, channels)

The error appears here in this dummy model: 错误出现在此虚拟模型中:

inputs = Input(shape=(96, 96, 3))
x = MyCustomLayer()(inputs)
x = Flatten()(x)
x = Activation("relu")(x)
x = Dense(1)(x)    
predictions = Activation("sigmoid")(x)
model = Model(inputs=inputs, outputs=predictions)

Thanks for all hints... 感谢所有提示...

TD;LR You should not mix Numpy inside Keras layers. TD; LR您不应该在Keras层中混合Numpy。 Keras uses Tensorflow underneath because it has to track all the computations to be able to compute the gradients in the backward phase. Keras在下面使用Tensorflow,因为它必须跟踪所有计算才能在反向阶段计算梯度。

If you dig in Tensorflow, you will see that it almost covers all the Numpy functionality (or even extends it) and if I remember correctly, Tensorflow functionality can be accessed through the Keras backend (K). 如果您深入研究Tensorflow,您会发现它几乎涵盖了所有Numpy功能(甚至扩展了它),如果我没记错的话,可以通过Keras后端(K)访问Tensorflow功能。

What are the advance calculations/functions you need? 您需要哪些高级计算/功能?

i think that this kinda process should apply before the model because the process does not contain variables so it cant be optimized. 我认为这种流程应在模型之前应用,因为该流程不包含变量,因此无法进行优化。

K.eval(inputs) does not work beacuse you are trying to evaluate a placeholder not variable placeholders has not values for evaluate. K.eval(inputs)不起作用,因为您正在尝试评估占位符,而不是变量占位符没有评估值。 if you want get values you should feed it or you can make a list from tensors one by one with tf.unstack() 如果您想获取值,则应该输入它,也可以使用tf.unstack()从张量中列出一个列表

nparray = tf.unstack(tf.unstack(tf.unstack(inputs,96,0),96,0),3,0)

your call function is wrong because returns a variable you should return a constant: 您的调用函数是错误的,因为返回变量,您应该返回常量:

result = K.constant(nparray, dtype='float32')
return result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM