Tensorflow,如何将2D张量(矩阵)与1D向量中的相应元素相乘 [英] Tensorflow, how to multiply a 2D tensor (matrix) by corresponding elements in a 1D vector
问题描述
我有一个形状为[batch x dim]
的2D矩阵M
,我有一个形状为[batch]
的矢量V
.如何将矩阵中的每一列乘以V中的对应元素?那就是:
I have a 2D matrix M
of shape [batch x dim]
, I have a vector V
of shape [batch]
. How can I multiply each of the columns in the matrix by the corresponding element in the V? That is:
我知道低效的numpy实现看起来像这样:
I know an inefficient numpy implementation would look like this:
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)
在张量流中,给定两个张量,最有效的方法是什么?
In tensorflow, given two tensors, what is the most efficient way to achieve this?
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
上扩展暗淡效果,我们可以使用tf.newaxis
(在较新版本中)或tf.expand_dims
或使用tf.reshape
-
In NumPy, we would need to make V
2D
and then let broadcasting do the element-wise multiplication (i.e. Hadamard product). I am guessing, it should be the same on tensorflow
. So, for expanding dims on tensorflow
, we can use tf.newaxis
(on newer versions) or tf.expand_dims
or a reshape with tf.reshape
-
tf.multiply(M, V[:,tf.newaxis])
tf.multiply(M, tf.expand_dims(V,1))
tf.multiply(M, tf.reshape(V, (-1, 1)))
这篇关于Tensorflow,如何将2D张量(矩阵)与1D向量中的相应元素相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!