Skip to main content
 首页 » 编程设计

python之如何在Tensorflow中乘以多维张量的其中一个维度

2024年09月03日31mfrbuaa

我有如下张量:

y = tf.placeholder(tf.float32, [None, 3],name="output") 

我想乘以最后一个 3 维张量。
我试过这个:

outputs_with_multiplier = y 
outputs_with_multiplier[-1] = tf.multiply(outputs_with_multiplier[-1],tf.constant(2.0)) 

我收到以下错误:

  outputs_with_multiplier[-1] = tf.multiply(outputs_with_multiplier[-1],tf.constant(2.0)) 
TypeError: 'Tensor' object does not support item assignment 

我查了以下问题以供引用,但我没有发现它们有帮助,可能是因为我没有理解它们。
1) Tensorflow - matmul of input matrix with batch data
2) Tensor multiplication in Tensorflow

请帮助我乘以 Tensors 维度,使其顺利运行。

例如,如果这是我的 y = [[1,2,3],[2,3,4],[3,4,5],[2,5,7],[8, 9,10],[0,3,2]] 所以我想让它 outputs_with_multiplier = [[1,2,6],[2,3,8],[3,4, 10],[2,5,14],[8,9,20],[0,3,4]]

如果有任何解决方案,请告诉我。

请您参考如下方法:

您不能进行项目分配,但可以创建一个新的 Tensor。关键是前两列乘以 1,第三列乘以 2。

x = tf.placeholder(tf.float32, [None, 3], name="output") 
y = tf.constant([[1.0, 1.0, 2.0]]) 
z = tf.multiply(x, y) 
 
sess = tf.Session() 
sess.run(z, feed_dict={x: [[1,2,3],[2,3,4],[3,4,5],[2,5,7],[8,9,10],[0,3,2]]})