【问题标题】:Keras Custom Layer with advanced calculations具有高级计算功能的 Keras 自定义层
【发布时间】:2023-03-10 06:40:01
【问题描述】:

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

感谢所有提示...

【问题讨论】:

  • 能否提供出现错误的代码?您得到的错误与调用此函数时输入变量没有很好定义的事实有关。见github.com/tensorflow/tensorflow/issues/10632
  • 您必须使用后端函数(如果您使用的是 TensorFlow,则使用 TensorFlow)来实现这些高级计算。没有解决此问题的方法,因为梯度需要通过您的层传播。你也不能使用 K.eval。
  • 这段代码究竟做了什么?你的期望是什么?

标签: python tensorflow keras


【解决方案1】:

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

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

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

【讨论】:

  • 例如numpy.histogram
  • 我明白了……我坚持我的观点。我会尝试找到在 tensorflow(或 Keras 的后端)中编程此函数的方法,因为将数据输入/输出 tensorflow 会话的成本很高,然后会引入延迟。
  • 也许numpy.histogram 可以通过组合一些keras.backend 函数或Tensorflow 函数在Keras 层中完成,例如tf.math.roundtf.dtypes.casttf.math.bincount ... ?
  • 这就是我的意思,是的:D
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 2019-12-27
    • 1970-01-01
    • 2018-09-26
    • 2020-05-15
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多