Home > Enterprise >  Problem mapping a function on tensors using TensorFlow
Problem mapping a function on tensors using TensorFlow

Time:10-26

I have to execute a simple function that subtract elements of two lists and put the result in a new list using TensorFlow fn_map function. The code without this function works fine, but when I modify it using fn_map the following error occurs:

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)

Here is the code:

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)

What is the problem?

CodePudding user response:

Maybe just trying doing element-wise subtraction on your tensors a and b without any loops:

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.]
  • Related