Use dictionary in tf.function input_signature in Tensorflow 2.0

m33*_*33n 9 python tensorflow2.0

I am using Tensorflow 2.0 and facing the following situation:

@tf.function
def my_fn(items):
    .... #do stuff
    return
Run Code Online (Sandbox Code Playgroud)

If items is a dict of Tensors like for example:

item1 = tf.zeros([1, 1])
item2 = tf.zeros(1)
items = {"item1": item1, "item2": item2}
Run Code Online (Sandbox Code Playgroud)

Is there a way of using input_signature argument of tf.function so I can force tf2 to avoid creating multiple graphs when item1 is for example tf.zeros([2,1]) ?

Sve*_*rdt 6

输入签名必须是一个列表,但列表中的元素可以是字典或张量规范列表。在你的情况下,我会尝试:(name属性是可选的)

signature_dict = { "item1": tf.TensorSpec(shape=[2], dtype=tf.int32, name="item1"),
                   "item2": tf.TensorSpec(shape=[], dtype=tf.int32, name="item2") } 
              

# don't forget the brackets around the 'signature_dict'
@tf.function(input_signature = [signature_dict])
def my_fn(items):
    .... # do stuff
    return

# calling the TensorFlow function
my_fun(items)
Run Code Online (Sandbox Code Playgroud)

但是,如果要调用由my_fn.创建的特定具体函数,则必须解压缩字典。您还必须nametf.TensorSpec.

# creating a concrete function with an input signature as before but without
# brackets and with mandatory 'name' attributes in the TensorSpecs 
my_concrete_fn = my_fn.get_concrete_function(signature_dict)
                                             
# calling the concrete function with the unpacking operator
my_concrete_fn(**items)
Run Code Online (Sandbox Code Playgroud)

这很烦人,但应该在 TensorFlow 2.3 中解决。(参见“具体函数”TF 指南的结尾)