如何在TensorFlow中制作"动态"函数签名?



我一直在尝试制作一个"动态的";使用@tf.function(input_signature=[...])与TensorFlow函数签名。更具体地说,我需要找到一种方法,使其中一个参数为tf.TensorSpec(shape=[None, None], dtype=tf.float32)None

我正在尝试以下内容:

@tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.string), tf.TensorSpec(shape=[None, None], dtype=tf.float32)])
def generate_one_step(self, inputs, states=None):
...

,但由于第二个参数在某些情况下也可以是None,我得到以下错误:

ValueError: When input_signature is provided, all inputs to the Python function must be convertible to tensors:
inputs: (
tf.Tensor([b'Test '], shape=(1,), dtype=string),
None)
input_signature: (
TensorSpec(shape=(None,), dtype=tf.string, name=None),
TensorSpec(shape=(None, None), dtype=tf.float32, name=None)).

我意识到关于第一个输入的形状也可能存在错误,但我不确定如何使一个"变量";

解决这个问题的方法是指定两个不同的函数。值得指出的是,TF签名不像Java签名那样工作,因此您应该以不同的方式命名您的函数。

我代码:

@tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.string), tf.TensorSpec(shape=[None, None], dtype=tf.float32)])
def generate_one_step(self, inputs, states):
...
@tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.string)])
def generate_one_step_none(self, inputs):
states = None

最新更新