繁体   English   中英

tf.function 调用子层时出现输入签名错误

[英]tf.function with input signature errors out when calling a sub layer

以下工作正常

class MyModel(tf.Module):
    def __init__(self):
        super(MyModel, self).__init__(name='MyModel')
        self.dense = tf.keras.layers.Dense(50)

    @tf.function
    def __call__(self, inputs):
        return self.dense(inputs)

my_model = MyModel()
my_model(tf.ones((4, 42, 30, 200), name='features'))

但是,当我尝试在tf.function装饰器中明确指定输入签名时,代码失败:

class MyModel(tf.Module):
    def __init__(self):
        super(MyModel, self).__init__(name='MyModel')
        self.dense = tf.keras.layers.Dense(50)

    @tf.function(input_signature=[
        tf.TensorSpec(shape=(None, None, None, None), dtype=tf.float32)
    ])
    def __call__(self, inputs):
        return self.dense(inputs)

my_model = MyModel()
my_model(tf.ones((4, 42, 30, 200), name='features'))

导致以下错误:

ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.

有人可以解释我在这里做错了什么吗?

您的tf.Module tf.keras.Model创建; a Keras model 有两个不同的阶段:

  1. model 结构,其中每一层都根据输入形状定义
  2. model 执行,其中内置的 model 用于运行正向传递。

When you specify the input shape of the first layer of your model (using the input_shape attribute of Dense or the tf.keras.layers.Input layer), Keras is able to execute the first phase, model construction, because it now knows that the第一个权重矩阵应该类似于input_shape[-1] * <number_units> (在您的情况下为 50)。

When you, instead, do not specify the input shape, what happens is that Keras can't execute the model construction on the model definition time, but it has to wait until the first input is passed to the model; 此输入具有定义的形状(在您的情况下为(4, 42, 30, 200) ),因此它可以连续运行 model 构造和执行。

当您没有指定形状时,所有这些都会发生。

但是在第二个示例中,您指定了tf.Module__call__方法的输入形状,该方法传播到tf.keras.Model__call__

因此,这里发生的情况是您要求 Keras model 连续执行 model 构造和执行,但是由于没有定义形状(因为您没有传递),因此input_shape[-1] is None (None, None, None, None) input_shape[-1] is None ) Keras 只是无法定义 model。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM