Custom Keras Layer fails with "TypeError: Could not build a TypeSpec for KerasTensor"

Custom Keras Layer fails with "TypeError: Could not build a TypeSpec for KerasTensor"

我将我的问题简化为这个非常基本的例子:

from tensorflow import keras
from tensorflow.keras import layers

class MyLayer(layers.Layer):
    def __init__(self, z):
        super(MyLayer, self).__init__()
        self.z = z

    def call(self, inputs):
        return inputs * self.z
      
inputs = keras.Input(shape=(2,))
layer = MyLayer(inputs)
z = layer(inputs)

model = keras.Model(inputs=inputs, outputs=z)

失败

TypeError: Could not build a TypeSpec for <KerasTensor: shape=(None, 2) dtype=float32 (created by layer 'tf.math.multiply_17')> with type KerasTensor

你知道问题出在哪里吗?

您不能将 Keras 符号张量与图 mode 中的 Tensorflow 张量相乘。有几种方法可以做你想做的 IIUC,这里是一个选项,假设你想将两个张量传递给 MyLayer:

from tensorflow import keras
from tensorflow.keras import layers

class MyLayer(layers.Layer):
    def __init__(self):
        super(MyLayer, self).__init__()

    def call(self, inputs):
        x, y = inputs
        return x * y
      
inputs = keras.Input(shape=(2,))
layer = MyLayer()
z = layer([inputs, inputs])

model = keras.Model(inputs=inputs, outputs=z)