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

时间:2019-02-18 10:18:15

标签: python tensorflow keras

我想编写一些自定义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)

感谢所有提示...

2 个答案:

答案 0 :(得分:0)

TD; LR请勿在Keras层内部混合Numpy。 Keras在其下使用Tensorflow,因为它必须跟踪所有计算以能够在反向阶段计算梯度。

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

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

答案 1 :(得分:0)

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

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