TensorFlow之tf.multiply和tf.matmul

在TF中如何運行乘法,如果是逐元素相乘或者是矩陣的乘法,如何表達。

tf.multiply

example:

import tensorflow as tf

a = tf.get_variable("a", dtype=tf.float32, shape=(2, 3), initializer=tf.constant_initializer(2.))
b = tf.get_variable("b", dtype=tf.float32, shape=(2, 3), initializer=tf.constant_initializer(2.))
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)
print(sess.run(tf.multiply(a, b)))

結果:

[[4. 4. 4.]
 [4. 4. 4.]]

tf.multiply實現的是逐個元素相乘。相乘的Tensor可以是一樣的shape,也可以是不一樣的Shape。比如將a中的shape=(2,3)shape=(2,3)換成shape=(1)shape=(1)也同樣成立。感興趣的可以試試。
tf2.0中已經放到tf.math裏面了,變成了tf.math.multiply(x,y).

tf.matmul

example

import tensorflow as tf

a = tf.get_variable("a", dtype=tf.float32, shape=(3,2), initializer=tf.constant_initializer(2.))
b = tf.get_variable("b", dtype=tf.float32, shape=(2, 3), initializer=tf.constant_initializer(3.))
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)
print(sess.run(tf.matmul(a, b)))

結果:

[[12. 12. 12.]
 [12. 12. 12.]
 [12. 12. 12.]]

tf.matmul就是矩陣的點乘了。兩個矩陣的shape需要保證a的列數和b的行數相等。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章