在Tensorflow中逐行矢量化两个不同形状矩阵的逐行元素乘积

问题描述 投票:1回答:1

在Tensorflow中,假设我有两个矩阵MN,我怎样才能得到一个张量为(i, j)元素是第i行M和第j行N的元素乘积?

python numpy matrix tensorflow vectorization
1个回答
2
投票

这里有一个技巧:将两个矩阵扩展到3D并进行元素乘法(a.k.a.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以及任何基于元素的二元运算(sum,product,division,...)。这是一个逐行元素和张量的例子:

# 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]]]
© www.soinside.com 2019 - 2024. All rights reserved.