使用 TensorFlow 在张量上映射函数的问题

Problem mapping a function on tensors using TensorFlow

我必须执行一个简单的函数,将两个列表的元素相减,然后使用 TensorFlow fn_map 函数将结果放入一个新列表中。没有这个功能的代码工作正常,但是当我使用 fn_map 修改它时,出现以下错误:

Exception has occurred: ValueError
in user code:

    /home/imene/ESS/ess.py:359 sup  *
        for el1 in inputs[0]:
    /home/imene/anaconda3/envs/master/lib/python3.6/site-packages/tensorflow/python/autograph/operators/control_flow.py:420 for_stmt
        iter_, extra_test, body, get_state, set_state, symbol_names, opts)
    /home/imene/anaconda3/envs/master/lib/python3.6/site-packages/tensorflow/python/autograph/operators/control_flow.py:485 _known_len_tf_for_stmt
        n = py_builtins.len_(iter_)
    /home/imene/anaconda3/envs/master/lib/python3.6/site-packages/tensorflow/python/autograph/operators/py_builtins.py:249 len_
        return _tf_tensor_len(s)
    /home/imene/anaconda3/envs/master/lib/python3.6/site-packages/tensorflow/python/autograph/operators/py_builtins.py:277 _tf_tensor_len
        'len requires a non-scalar tensor, got one of shape {}'.format(shape))

    ValueError: len requires a non-scalar tensor, got one of shape []
  File "/tmp/tmpgps8mh9_.py", line 33, in tf__sup
    ag__.for_stmt(ag__.ld(inputs)[0], None, loop_body_1, get_state_1, set_state_1, (), {'iterate_names': 'el1'})

During handling of the above exception, another exception occurred:

  File "/home/imene/ESS/ess.py", line 366, in supp
    ss =tf.map_fn(sup, inputs, dtype = tf.float32)
  File "/home/imene/ESS/ess.py", line 373, in <module>
    ss  = supp(ab)

代码如下:

import tensorflow as tf


a = [1, 3, 5, 8] 
b = [1, 5, 3, 60]


def supp(inputs):
    def sup(inputs):
        ss = []
        for el1 in inputs[0]:
            for el2 in inputs[1]:
                ss.append(el1 - el2)
        return ss  
     
    ss = tf.map_fn(sup, inputs, dtype=tf.float32)
    return ss

a = tf.convert_to_tensor(a)      
b = tf.convert_to_tensor(b)  
ab = tf.convert_to_tensor([a, b])

ss  = supp(ab)
print(ss)

有什么问题?

也许只是尝试在没有任何循环的情况下对张量 ab 进行逐元素减法:

import tensorflow as tf

a = [1, 3, 5, 8] 
b = [1, 5, 3, 60]

def supp(inputs):
    def sup(inputs):
        return tf.cast(inputs[0] - inputs[1], dtype=tf.float32)  
     
    ss = tf.map_fn(sup, inputs, dtype=tf.float32)
    return ss

a = tf.convert_to_tensor(a)      
b = tf.convert_to_tensor(b)  

ss  = supp([a, b])
print(ss)
# tf.Tensor([  0.  -2.   2. -52.], shape=(4,), dtype=float32)
print(ss.numpy())
# [  0.  -2.   2. -52.]