在Tensorflow中,说我有两个矩阵MN,如何获得张量的张量,其(i, j)元素是M的第i行和?

最佳答案

这是个窍门:将两个矩阵都扩展到3D并进行图元乘法(又称为Hadamard乘积)。



# Let `a` and `b` be the rank 2 tensors, with the same 2nd dimension
lhs = tf.expand_dims(a, axis=1)
rhs = tf.expand_dims(b, axis=0)
products = lhs * rhs


让我们检查一下它是否有效:

tf.InteractiveSession()

# 2 x 3
a = tf.constant([
  [1, 2, 3],
  [3, 2, 1],
])

# 3 x 3
b = tf.constant([
  [2, 1, 1],
  [2, 2, 0],
  [1, 2, 1],
])

lhs = tf.expand_dims(a, axis=1)
rhs = tf.expand_dims(b, axis=0)
products = lhs * rhs
print(products.eval())

# [[[2 2 3]
#   [2 4 0]
#   [1 4 3]]
#
#  [[6 2 1]
#   [6 4 0]
#   [3 4 1]]]




相同的技巧实际上也适用于numpy以及任何按元素进行二进制运算(求和,乘积,除法...)。这是按行逐元素求和张量的示例:

# 2 x 3
a = np.array([
  [1, 2, 3],
  [3, 2, 1],
])

# 3 x 3
b = np.array([
  [2, 1, 1],
  [2, 2, 0],
  [1, 2, 1],
])

lhs = np.expand_dims(a, axis=1)
rhs = np.expand_dims(b, axis=0)
sums = lhs + rhs

# [[[2 2 3]
#   [2 4 0]
#   [1 4 3]]
#
#  [[6 2 1]
#   [6 4 0]
#   [3 4 1]]]

关于python - 在Tensorflow中向量化两个不同形状矩阵的逐行逐元素乘积,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49089407/

10-09 07:29
查看更多