Tensorflow,如何将二维张量(矩阵)乘以一维向量中的相应元素
Tensorflow, how to multiply a 2D tensor (matrix) by corresponding elements in a 1D vector
我有一个形状为 [batch x dim]
的二维矩阵 M
,我有一个形状为 [batch]
的向量 V
。如何将矩阵中的每一列乘以 V 中的相应元素?即:
我知道一个低效的 numpy 实现看起来像这样:
import numpy as np
M = np.random.uniform(size=(4, 10))
V = np.random.randint(4)
def tst(M, V):
rows = []
for i in range(len(M)):
col = []
for j in range(len(M[i])):
col.append(M[i][j] * V[i])
rows.append(col)
return np.array(rows)
在tensorflow中,给定两个张量,最有效的方法是什么?
import tensorflow as tf
sess = tf.InteractiveSession()
M = tf.constant(np.random.normal(size=(4,10)), dtype=tf.float32)
V = tf.constant([1,2,3,4], dtype=tf.float32)
在 NumPy 中,我们需要制作 V
2D
然后让广播进行元素乘法(即 Hadamard 乘积)。我猜,在 tensorflow
上应该是一样的。因此,为了在 tensorflow
上扩展 dims,我们可以使用 tf.newaxis
(在较新的版本上)或 tf.expand_dims
或使用 tf.reshape
-
进行重塑
tf.multiply(M, V[:,tf.newaxis])
tf.multiply(M, tf.expand_dims(V,1))
tf.multiply(M, tf.reshape(V, (-1, 1)))
除了@Divakar 的回答之外,我想说明 M
和 V
的顺序无关紧要。 tf.multiply
似乎也 .
示例:
In [55]: M.eval()
Out[55]:
array([[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]], dtype=int32)
In [56]: V.eval()
Out[56]: array([10, 20, 30], dtype=int32)
In [57]: tf.multiply(M, V[:,tf.newaxis]).eval()
Out[57]:
array([[ 10, 20, 30, 40],
[ 40, 60, 80, 100],
[ 90, 120, 150, 180]], dtype=int32)
In [58]: tf.multiply(V[:, tf.newaxis], M).eval()
Out[58]:
array([[ 10, 20, 30, 40],
[ 40, 60, 80, 100],
[ 90, 120, 150, 180]], dtype=int32)
我有一个形状为 [batch x dim]
的二维矩阵 M
,我有一个形状为 [batch]
的向量 V
。如何将矩阵中的每一列乘以 V 中的相应元素?即:
我知道一个低效的 numpy 实现看起来像这样:
import numpy as np
M = np.random.uniform(size=(4, 10))
V = np.random.randint(4)
def tst(M, V):
rows = []
for i in range(len(M)):
col = []
for j in range(len(M[i])):
col.append(M[i][j] * V[i])
rows.append(col)
return np.array(rows)
在tensorflow中,给定两个张量,最有效的方法是什么?
import tensorflow as tf
sess = tf.InteractiveSession()
M = tf.constant(np.random.normal(size=(4,10)), dtype=tf.float32)
V = tf.constant([1,2,3,4], dtype=tf.float32)
在 NumPy 中,我们需要制作 V
2D
然后让广播进行元素乘法(即 Hadamard 乘积)。我猜,在 tensorflow
上应该是一样的。因此,为了在 tensorflow
上扩展 dims,我们可以使用 tf.newaxis
(在较新的版本上)或 tf.expand_dims
或使用 tf.reshape
-
tf.multiply(M, V[:,tf.newaxis])
tf.multiply(M, tf.expand_dims(V,1))
tf.multiply(M, tf.reshape(V, (-1, 1)))
除了@Divakar 的回答之外,我想说明 M
和 V
的顺序无关紧要。 tf.multiply
似乎也
示例:
In [55]: M.eval()
Out[55]:
array([[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]], dtype=int32)
In [56]: V.eval()
Out[56]: array([10, 20, 30], dtype=int32)
In [57]: tf.multiply(M, V[:,tf.newaxis]).eval()
Out[57]:
array([[ 10, 20, 30, 40],
[ 40, 60, 80, 100],
[ 90, 120, 150, 180]], dtype=int32)
In [58]: tf.multiply(V[:, tf.newaxis], M).eval()
Out[58]:
array([[ 10, 20, 30, 40],
[ 40, 60, 80, 100],
[ 90, 120, 150, 180]], dtype=int32)