TensorFlow中矩阵和向量的高效逐元素乘法 [英] Efficient element-wise multiplication of a matrix and a vector in TensorFlow
问题描述
乘以2维张量(矩阵)的最有效方法是什么:
What would be the most efficient way to multiply (element-wise) a 2D tensor (matrix):
x11 x12 .. x1N
...
xM1 xM2 .. xMN
通过垂直向量:
w1
...
wN
获得一个新矩阵:
x11*w1 x12*w2 ... x1N*wN
...
xM1*w1 xM2*w2 ... xMN*wN
为了提供一些背景信息,我们有一个批处理中的M
个数据样本可以并行处理,并且每个N
元素样本都必须乘以存储在变量中的权重w
才能最终选择最大Xij*wj
每行i
.
To give some context, we have M
data samples in a batch that can be processed in parallel, and each N
-element sample must be multiplied by weights w
stored in a variable to eventually pick the largest Xij*wj
for each row i
.
推荐答案
执行此操作的最简单代码取决于 numpy的广播行为:
The simplest code to do this relies on the broadcasting behavior of tf.multiply()
*, which is based on numpy's broadcasting behavior:
x = tf.constant(5.0, shape=[5, 6])
w = tf.constant([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
xw = tf.multiply(x, w)
max_in_rows = tf.reduce_max(xw, 1)
sess = tf.Session()
print sess.run(xw)
# ==> [[0.0, 5.0, 10.0, 15.0, 20.0, 25.0],
# [0.0, 5.0, 10.0, 15.0, 20.0, 25.0],
# [0.0, 5.0, 10.0, 15.0, 20.0, 25.0],
# [0.0, 5.0, 10.0, 15.0, 20.0, 25.0],
# [0.0, 5.0, 10.0, 15.0, 20.0, 25.0]]
print sess.run(max_in_rows)
# ==> [25.0, 25.0, 25.0, 25.0, 25.0]
* 在旧版本的TensorFlow中,tf.multiply()
被称为tf.mul()
.您还可以使用*
运算符(即xw = x * w
)执行相同的操作.
* In older versions of TensorFlow, tf.multiply()
was called tf.mul()
. You can also use the *
operator (i.e. xw = x * w
) to perform the same operation.
这篇关于TensorFlow中矩阵和向量的高效逐元素乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!