TensorFlow Create Tensor | What is Tensor in TensorFlow

In this tutorial, you’ll learn how to create your own tensors within TensorFlow. Then, be able to use these tensors on your own deep learning projects! This tutorial will teach you the basics of what a tensor is, why they are important, and how to create a tensor. To create your own tensor all you need is some data! So head over here if you want to learn more about creating your own tensor in TensorFlow. I highly recommend you get this book, “Deep Learning with TensorFlow 2 and Keras” to learn Deep Learning.

What is Tensor in TensorFlow?

Tensors are the fundamental building blocks of TensorFlow. Tensors are n-dimensional arrays of numbers that can be visualized as a table with two indices, one along its vertical axis and one along its horizontal axis. In simple words, a tensor is a generalization of vectors and matrices to higher dimensions.

Why are tensors important for deep learning?

Tensors give deep learning models the ability to represent complicated math operations as linear algebra equations, speeding up computations and improving accuracy.

Create Tensor in TensorFlow

You can use these two methods to create a tensor in TensorFlow.

Method 1: tf.constant()

This method is useful when you don’t want to change the values of the tensor because it doesn’t allow you to assign values after the first creation.

Example 1: Zero-Dimensional Tensor (Scalar)

This is a zero-dimensional tensor also called a scalar that has no dimension.

# Import TensorFlow as tf
import tensorflow as tf

# Create a zero dimensional tensor
a = tf.constant(5)

# Display tensor
print(a)

# Display dimension of tensor
print(a.ndim)

Output:

tf.Tensor(5, shape=(), dtype=int32)
0

Example 2: One-Dimensional Tensor (Vector)

This is a one-dimensional tensor also called a vector.

# Import TensorFlow as tf
import tensorflow as tf

# Create a one dimensional tensor
b = tf.constant([10,20])

# Display tensor
print(b)

# Display dimension of tensor
print(b.ndim)

Output:

tf.Tensor([10 20], shape=(2,), dtype=int32)
1

Example 3: Multi-Dimensional Tensor (Matrix)

This is a multi-dimensional tensor also called a matrix that has more than 1 dimension.

# Import TensorFlow as tf
import tensorflow as tf

# Create a multi-dimensional tensor
c = tf.constant([[10,20],
                [30,40]])

# Display tensor
print(c)

# Display dimension of tensor
print(c.ndim)

Output:

tf.Tensor(
[[10 20]
 [30 40]], shape=(2, 2), dtype=int32)
2

Method 2: tf.Variable()

This method is useful if you want to change the values of the tensor after its initial creation.

# Import TensorFlow as tf
import tensorflow as tf

# Create a tensor
a = tf.Variable([[10, 20],
                 [30, 40],
                 [50, 60]])

# Display tensor
print(a)

Output:

<tf.Variable 'Variable:0' shape=(3, 2) dtype=int32, numpy=
array([[10, 20],
       [30, 40],
       [50, 60]])>

Leave a Comment

Your email address will not be published.