Skip to main content
 首页 » 编程设计

python之TensorFlow:相当于 tf.add_n 的产品

2024年10月17日29emanlee

是否有与 tf.add_n 等效的乘积,返回张量列表的元素乘积?

请您参考如下方法:

解决方案一:

您可以使用高阶函数 tf.foldl 和 tf.foldr。这是一个例子:

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() 

结果: [240 8 4 108]

解决方案 2: 您可以使用 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() 

结果:

[[ 5 2 4 3]

[2 2 1 6]

[24 2 1 6]]

产品 [240 8 4 108]