在Tensorflow中,假设我有两个矩阵M和N,如何才能得到其(i, j)元素是M的第一行和N的第j行的按元素方向积的张量?
发布于 2018-03-04 23:25:02
这里有一个窍门:将两个矩阵展开为3D,并进行逐次乘(即a。哈达玛产品)。
# 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]]]https://stackoverflow.com/questions/49089407
复制相似问题