tf.reduce_mean
和tf.reduce_prod
等函数执行元素操作以减少沿轴的张量。我有一个形状为R
的张量(1000, 3, 3)
,一个3x3矩阵列表。我想要做的是矩阵将它们相乘,所以我保持一个3x3矩阵。如果这是numpy我可以使用
np.linalg.multi_dot(R)
我怎么能在张量流中做到这一点?
答案 0 :(得分:4)
您可以使用tf.scan:tf.scan(lambda a, b: tf.matmul(a, b), R)[-1]
import tensorflow as tf
import numpy as np
R = np.random.rand(10, 3, 3)
R_reduced = np.linalg.multi_dot(R)
R_reduced_t = tf.scan(lambda a, b: tf.matmul(a, b), R)[-1]
with tf.Session() as sess:
R_reduced_val = sess.run(R_reduced_t)
diff = R_reduced_val - R_reduced
print(diff)
打印:
[[ -3.55271368e-15 0.00000000e+00 0.00000000e+00]
[ 1.77635684e-15 0.00000000e+00 3.55271368e-15]
[ -1.77635684e-15 3.55271368e-15 0.00000000e+00]]