Hi everyone, In this TensorFlow 2.0 tutorial we will look at how we can mathematical operations. As you already know we can do mathematical operations with NumPy. If we want to use GPU to train our model we can’t use NumPy for mathematical operation. Let’s look at closer how we do those operations.


Firstly, we need to import tensorflow and numpy libraries.

import tensorflow as tf
import numpy as np

Elementwise Mathematical Operations


Create two tensor for elementwise sum operation.

x = tf.constant([1,2,3,4])
y = tf.constant([5,6,7,8])
z = tf.add(x,y)
print(z)
tf.Tensor([ 6  8 10 12], shape=(4,), dtype=int32)

Create two tensor for elementwise subtract operation.

x = tf.constant([1,2,3,4])
y = tf.constant([8,2,6,9])
z = tf.subtract(x,y)
print(z)
tf.Tensor([-7  0 -3 -5], shape=(4,), dtype=int32)

Create two tensor for elementwise divide operation.

x = tf.constant([8,2,6,4])
y = tf.constant([2,2,3,8])
zip = tf.divide(x,y)
print(z)
tf.Tensor([4.  1.  2.  0.5], shape=(4,), dtype=float64)

Create two tensor for elementwise multiplication.

x = tf.constant([3,10,6,4])
y = tf.constant([2,4,7,8])
z = tf.multiply(x,y)
print(z)
tf.Tensor([ 6 40 42 32], shape=(4,), dtype=int32)

Multiply tensor and scalar number by elementwise multiply

x = tf.constant([[1,2,3],[4,5,6],[7,8,9]])
z = x*5
print(z)

x = tf.constant([[1,2,3],[4,5,6],[7,8,9]])
z = x + 5
print(z)

x = tf.constant([[1,2,3],[4,5,6],[7,8,9]])
z = x - 5
print(z)

x = tf.constant([[1,2,3],[4,5,6],[7,8,9]])
z = x / 5
print(z)

Using two different methods in TensorFlow, we can first multiply two tensors elementwise and then add them.

x = tf.constant([3,10,6,4])
y = tf.constant([1,5,9,3])
z = tf.tensordot(x,y, axes=1)
print(z)
print("---------------------")
z = tf.reduce_sum(x*y, axis=0)
print(z)
tf.Tensor(119, shape=(), dtype=int32) 
--------------------- 
tf.Tensor(119, shape=(), dtype=int32)

As we do in numPy, in tensorFlow too, we want to matrix multiplication we can do two diffrent way.

# matmul
x = tf.random.normal((2,3))
print(x)
print("--------------------")
y = tf.random.normal((3,4))
print(y)
print("--------------------")
z = tf.matmul(x,y)
print(z)
tf.Tensor(
[[ 0.35243663 -0.03096309 -1.00921   ]
 [ 0.3404678   0.0727164   1.491804  ]], shape=(2, 3), dtype=float32)
--------------------
tf.Tensor(
[[-0.480189   -0.77385694  0.06627358 -1.1215519 ]
 [-0.86899495 -0.32598338 -0.2432404   0.705484  ]
 [ 0.09199216 -0.8199832  -0.72130775  0.3183974 ]], shape=(3, 4), dtype=float32)
--------------------
tf.Tensor(
[[-0.23516884  0.5648931   0.7588397  -0.73844975]
 [-0.08944482 -1.510432   -1.0711733   0.14443448]], shape=(2, 4), dtype=float32)

# @
z = x @ y
print(z)
tf.Tensor( [[-0.23516884  0.5648931   0.7588397  -0.73844975]  [-0.08944482 -1.510432   -1.0711733   0.14443448]], shape=(2, 4), dtype=float32)