Python TensorFlow 中矩阵和向量的有效元素乘法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34192229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Efficient element-wise multiplication of a matrix and a vector in TensorFlow
提问by Andrzej Pronobis
What would be the most efficient way to multiply (element-wise) a 2D tensor (matrix):
乘以(逐元素)二维张量(矩阵)的最有效方法是什么:
x11 x12 .. x1N
...
xM1 xM2 .. xMN
by a vertical vector:
通过垂直向量:
w1
...
wN
to obtain a new matrix:
获得一个新矩阵:
x11*w1 x12*w2 ... x1N*wN
...
xM1*w1 xM2*w2 ... xMN*wN
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
.
为了给出一些上下文,我们有M
一批可以并行处理的数据样本,并且每个N
元素样本必须乘以w
存储在变量中的权重,以最终Xij*wj
为每一行选择最大的i
。
采纳答案by mrry
The simplest code to do this relies on the broadcasting behavior of tf.multiply()
*, which is based on numpy's broadcasting behavior:
执行此操作的最简单代码依赖于*的广播行为,该行为基于numpy 的广播行为:tf.multiply()
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]
*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 中,tf.multiply()
被称为tf.mul()
. 您还可以使用*
运算符(即xw = x * w
)来执行相同的操作。