减少张量流中的矩阵数组

Hoo*_*ked 2 python matrix tensorflow

功能类似于tf.reduce_meantf.reduce_prod执行元素明智的操作以减少沿轴的张量。我有一个R形状(1000, 3, 3)为 3x3 矩阵的张量。我想做的是将它们矩阵相乘,所以我保留一个 3x3 矩阵。如果这是 numpy 我可以使用

np.linalg.multi_dot(R)
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 tensorflow 中做到这一点?

Gee*_*rtH 5

您可以使用tf.scantf.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)
Run Code Online (Sandbox Code Playgroud)

这打印:

[[ -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]]
Run Code Online (Sandbox Code Playgroud)