繁体   English   中英

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

[英]Keras Custom Layer with advanced calculations

我想编写一些自定义Keras图层并在该图层中进行一些高级计算,例如使用Numpy,Scikit,OpenCV ...

我知道keras.backend中有一些数学函数可以对张量进行运算,但是我需要一些更高级的函数。

但是,我不知道如何正确执行此操作,我收到错误消息:
You must feed a value for placeholder tensor 'input_1' with dtype float and shape [...]

这是我的自定义层:

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)

错误出现在此虚拟模型中:

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)

感谢所有提示...

TD; LR您不应该在Keras层中混合Numpy。 Keras在下面使用Tensorflow,因为它必须跟踪所有计算才能在反向阶段计算梯度。

如果您深入研究Tensorflow,您会发现它几乎涵盖了所有Numpy功能(甚至扩展了它),如果我没记错的话,可以通过Keras后端(K)访问Tensorflow功能。

您需要哪些高级计算/功能?

我认为这种流程应在模型之前应用,因为该流程不包含变量,因此无法进行优化。

K.eval(inputs)不起作用,因为您正在尝试评估占位符,而不是变量占位符没有评估值。 如果您想获取值,则应该输入它,也可以使用tf.unstack()从张量中列出一个列表

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

您的调用函数是错误的,因为返回变量,您应该返回常量:

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

暂无
暂无

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

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