TensorFlow is an end-to-end machine learning library to create and deploy production and industry-ready complex machine learning models.
The TensorFlow library was created by the Google Brain team. It can train and run complex neural networks easily and supports many architectures, which create robust machine learning and deep neural network-based models.
Some competitor libraries to TensorFlow are PyTorch, CNTK (by Microsoft), and Apache MXNet.
In this shot, we’ll explore what a tensor is and how we can perform basic arithmetic operations on these tensors using the TensorFlow library.
A tensor is a multi-dimensional array similar to the NumPy arrays. For example, some tensors are shown below in the illustration:
Let’s explore how to create a tensor and then apply the basic mathematical operations on these tensors using TensorFlow.
The approach to apply mathematical operations on tensors is given below:
constant()
method from TensorFlow.Let’s see the code below:
import tensorflow as tf# Create a tensors using the constant() methodx = tf.constant(9)y = tf.constant(4)# Launch the default tensorflow graphsession = tf.Session()print("Operations on Scaler 1D tensors (which contains single value):")print("Apply addition on the tensors: ",session.run(x + y))print("Apply subtraction on the tensors: ",session.run(x - y))print("Apply multiplication on the tensors: ", session.run(x * y))# Create a tensors using the constant() methodx_arr = tf.constant([9, 11, 13])y_arr = tf.constant([1, 2, 3])print("Operations on 2D tensors:")print("Apply addition on the tensors: ",session.run(x_arr + y_arr))print("Apply subtraction on the tensors: ",session.run(x_arr - y_arr))print("Apply multiplication on the tensors: ", session.run(x_arr * y_arr))
Line 1: We import the required package.
Lines 4 and 5: We create the two constants using tensorflow
. These constants internally represent a scalar-tensor.
Line 8: We create the Session
object to allow the execution of operations on tensors.
Lines 10 to 12: We perform the four basic arithmetic operations on the scaler tensors using the run()
method. We also need to pass the expression to the run()
method which determines the operation that needs to be performed.
Lines 15 and 16: We again define two constants using tensorflow
. This time, these constants are 1-D tensors.
Lines 19 to 21: We perform the basic arithmetic operations on these 1-D tensors using the run()
method. We also pass an expression that determines the operation that needs to be performed among the 1-D tensors.