【发布时间】: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