Define and use Tensors using Simple Tensorflow Examples
Hello coders, in this post we will discuss Tensor and we will also see how to use them.
What is TensorFlow?
In Python for mathematical problems we used the TensorFlow library, it is a platform for machine learning.
Tensorflow is used for:
- Mathematical problems.
- GPU support
- Machine learning technique
Before we will proceed we will discuss some basics
We can define one/two/three-dimension tensors.
How to define one-dimensional Tensor?
We define tensor in Python using the list and then we convert it into a tensor.
We will use NumPy to create an array
import numpy as np arr = np.array([1, 56, 31, 15, 20])
From the output, you can see the dimension and shape of the array
import numpy as np arr = np.array([1, 56, 31, 15, 20]) print(arr) print (arr.ndim) print (arr.shape) print (arr.dtype)
Mathematical operations using tensors
Suppose that we have 2 arrays like this:
arr1 = np.array([(1,2,3),(4,5,6)]) arr2 = np.array([(7,8,9),(10,11,12)])
You can use the add function like this:
arr3 = tf.add(arr1,arr2)
So the whole code will be like this:
import numpy as np import tensorflow as tf arr1 = np.array([(1,2,3),(4,5,6)]) arr2 = np.array([(7,8,9),(10,11,12)]) arr3 = tf.add(arr1,arr2) sess = tf.Session() tensor = sess.run(arr3) print(tensor)
You can multiply arrays like this:
import numpy as np import tensorflow as tf arr1 = np.array([(1,2,3),(4,5,6)]) arr2 = np.array([(7,8,9),(10,11,12)]) arr3 = tf.multiply(arr1,arr2) sess = tf.Session() tensor = sess.run(arr3) print(tensor)
Leave a Reply