4
votes

Is it possible to run map_fn on a tensor with a single value?

The following works:

import tensorflow as tf
a = tf.constant(1.0, shape=[3])
tf.map_fn(lambda x: x+1, a)
#output: [2.0, 2.0, 2.0]

However this does not:

import tensorflow as tf
b = tf.constant(1.0)
tf.map_fn(lambda x: x+1, b)
#expected output: 2.0
  • Is it possible at all?
  • What am I doing wrong?

Any hints will be greatly appreciated!

2

2 Answers

2
votes

Well, I see you accepted an answer, which correctly states that tf.map_fn() is applying a function to elements of a tensor, and a scalar tensor has no elements. But it's not impossible to do this for a scalar tensor, you just have to tf.reshape() it before and after, like this code (tested):

import tensorflow as tf
b = tf.constant(1.0)

if () == b.get_shape():
    c = tf.reshape( tf.map_fn(lambda x: x+1, tf.reshape( b, ( 1, ) ) ), () ) 
else:
    c = tf.map_fn(lambda x: x+1, b)
#expected output: 2.0
with tf.Session() as sess:
    print( sess.run( c ) )

will output:

2.0

as desired.

This way you can factor this into an agnostic function that can take both scalar and non-scalar tensors as argument.

2
votes

No, this is not possible. As you probably saw it throws an error:

ValueError: elems must be a 1+ dimensional Tensor, not a scalar

The point of map_fn is to apply a function to each element of a tensor, so it makes no sense to use this for a scalar (single-element) tensor.

As to "what you are doing wrong": This is difficult to say without knowing what you're trying to achieve.