Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any function in TensorFlow equivalent to python reduce?

I want a function in TensorFlow which has the same effect as Pythion reduce()

For example, if I have a tensor a with value [a1, a2, a3] and a function func(), I want [func(a1, a2), func(func(a1, a2), a3)]. If a is a Python list I can simply do

from functools import reduce
# a = [a1, a2, a3]
A = reduce(func, a)

What if a is a Tensor (not a python list!) of TF object and I want the same A? If no alternative TF function, how can I do it effectively?

like image 651
M.Zhu Avatar asked Apr 30 '26 00:04

M.Zhu


1 Answers

If you actually mean reduce, so the tensorflow equivalent are tf.foldl and tf.foldr. Example:

elems = tf.constant(["hello", "my", "name", "is", "inigo", "montoya"])
tf.foldl(lambda a, x: a +" " + x, elems)
#<tf.Tensor: shape=(), dtype=string, numpy=b'hello my name is inigo montoya'>
tf.foldr(lambda a, x: a +" " + x, elems)
#<tf.Tensor: shape=(), dtype=string, numpy=b'montoya inigo is name my hello'>

However, according to your example you probably want tf.scan:

tf.scan(lambda a, x: a +" " + x, elems)
<tf.Tensor: shape=(6,), dtype=string, numpy=
    ([b'hello', b'hello my', b'hello my name', b'hello my name is',
    b'hello my name is inigo', b'hello my name is inigo montoya'], dtype=object)>
like image 173
chai Avatar answered May 02 '26 14:05

chai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!