簡體   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