TensorFlow can allow us to multiply tensors. We can use * or tf.multiply().
Difference Between tf.multiply() and tf.matmul() in TensorFlow – TensorFlow Tutorial
We also can multiply tensors of different shapes in tensorflow. We will discuss this topic in this tutorial.
Multiply two tensors with the same shapes
It is easy to understand, here is an example:
import tensorflow as tf import numpy as np x1 = tf.convert_to_tensor(np.array([[1, 2, 3],[2, 3, 4]]), dtype = tf.float32) x2 = tf.convert_to_tensor(np.array([[2, 2, 3],[2, 1, 4]]), dtype = tf.float32) z = x1 * x2 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print(sess.run(z))
The shape of x1 and x2 are both (2, 3). the result z will also be (2, 3)
z will be:
[[ 2. 4. 9.] [ 4. 3. 16.]]
Multiply two tensors with different shapes
Here is an example:
import tensorflow as tf import numpy as np x1 = tf.convert_to_tensor(np.array([[1, 2, 3],[2, 3, 4]]), dtype = tf.float32) x2 = tf.convert_to_tensor(np.array([[2, 2, 3]]), dtype = tf.float32) z = x1 * x2 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print(sess.run(z))
Here the shape of x1 is (2, 3), however, the shape of x2 is(1, 3)
Run this code, we can find the shape of z is (2, 3)
z is:
[[ 2. 4. 9.] [ 4. 6. 12.]]
From the result, we can find each element in x1 on axis = 0 will multiply x2.
If the shape of x2 is (3, )
import tensorflow as tf import numpy as np x1 = tf.convert_to_tensor(np.array([[1, 2, 3],[2, 3, 4]]), dtype = tf.float32) x2 = tf.convert_to_tensor(np.array([2, 2, 3]), dtype = tf.float32) z = x1 * x2 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print(sess.run(z))
Run this code, we can find z will be:
[[ 2. 4. 9.] [ 4. 6. 12.]]