user266044
user266044

Reputation: 69

TensorFlow: product equivalent of tf.add_n

Is there a product equivalent of tf.add_n, returning the elementwise product of a list of tensors?

Upvotes: 2

Views: 733

Answers (1)

Yao Zhang
Yao Zhang

Reputation: 5781

Solution 1:

You can use higher order functions tf.foldl and tf.foldr. Here is an example:

x = tf.constant([5, 2, 4, 3])
y = tf.constant([2, 2, 1, 6])
z = tf.constant([24, 2, 1, 6])

xyz=[x,y,z]
product = tf.foldl(tf.mul, xyz) 

with tf.Session() as sess:
    print product.eval()

Results: [240 8 4 108]

Solution 2: You can use tf.reduce_prod:

x = tf.constant([5, 2, 4, 3])
y = tf.constant([2, 2, 1, 6])
z = tf.constant([24, 2, 1, 6])

x=tf.reshape(x,[1,-1])
y=tf.reshape(y,[1,-1])
z=tf.reshape(z,[1,-1])
xyz=tf.concat(concat_dim=0, values=[x,y,z])

product = tf.reduce_prod(xyz, reduction_indices=0) 

with tf.Session() as sess:
    print xyz.eval()
    print product.eval()

Results:

xyz [[ 5 2 4 3]

[ 2 2 1 6]

[24 2 1 6]]

product [240 8 4 108]

Upvotes: 2

Related Questions