且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TensorFlow中矩阵和向量的高效逐元素乘法

更新时间:2022-06-04 03:10:55

执行此操作的最简单代码取决于 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.