张量流map_fn 上的单值张量

Ras*_*ner 5 python-3.x tensorflow

是否可以在具有单个值的张量上运行map_fn?

以下作品:

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]
Run Code Online (Sandbox Code Playgroud)

然而这并没有:

import tensorflow as tf
b = tf.constant(1.0)
tf.map_fn(lambda x: x+1, b)
#expected output: 2.0
Run Code Online (Sandbox Code Playgroud)
  • 有可能吗?
  • 我究竟做错了什么?

任何提示将不胜感激!

Pet*_*dan 3

好吧,我看到您接受了一个答案,该答案正确地指出将tf.map_fn()函数应用于张量的元素,而标量张量没有元素。但对于标量张量来说这并不是不可能的tf.reshape(),你只需要在之前和之后这样做,就像这段代码(经过测试):

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 ) )
Run Code Online (Sandbox Code Playgroud)

将输出:

2.0

如预期的。

通过这种方式,您可以将其分解为一个不可知函数,该函数可以将标量张量和非标量张量作为参数。