Skip to main content
TensorFlow Introduction
CHAPTER 06 Intermediate

TensorFlow Basics and Tensors

Updated: May 16, 2026
6 min read

# CHAPTER 6

TensorFlow Basics and Tensors

1. Introduction

The name "TensorFlow" describes exactly what the framework does: It takes multi-dimensional data structures called Tensors and "flows" them through a graph of mathematical operations (a Neural Network). If you want to master TensorFlow, you must understand what a Tensor is, how it differs from a standard Python list or a NumPy array, and how to manipulate it. In this chapter, we get our hands dirty with core TensorFlow code.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define what a Tensor is.
  • Create TensorFlow Constants and Variables.
  • Perform mathematical operations on Tensors.
  • Check Tensor shapes and data types.
  • Explain the concept of the Computation Graph.

3. What are Tensors?

A Tensor is a multi-dimensional array of numbers. It is almost identical to a NumPy array, with two major differences:
  1. 1. Tensors can be processed on a GPU (Graphics Processing Unit) for massive speedups.
  1. 2. Tensors automatically keep track of the mathematical operations applied to them, allowing TensorFlow to automatically calculate calculus gradients for Backpropagation (known as AutoGraph).

Tensor Dimensions (Ranks):

  • 0D Tensor (Scalar): A single number. (e.g., 5)
  • 1D Tensor (Vector): An array of numbers. (e.g., [1, 2, 3])
  • 2D Tensor (Matrix): A grid of numbers. (e.g., A grayscale image).
  • 3D Tensor: A cube of numbers. (e.g., A color image with Red, Green, Blue channels).
  • 4D Tensor: A batch of color images.

4. TensorFlow Constants

A tf.constant is a Tensor whose value cannot be changed once it is created.
python
12345678910111213141516
import tensorflow as tf

# Creating a 0D Tensor (Scalar)
scalar = tf.constant(42)
print(f"Scalar: {scalar}")

# Creating a 1D Tensor (Vector)
vector = tf.constant([1.0, 2.0, 3.0])
print(f"Vector Shape: {vector.shape}")

# Creating a 2D Tensor (Matrix)
matrix = tf.constant([
    [10, 20],
    [30, 40]
])
print(f"Matrix Dimensions: {matrix.ndim}") # Output: 2

5. TensorFlow Variables

While Constants never change, Neural Networks need to constantly update their Weights and Biases during training. We use tf.Variable for this.
python
1234567
# Create a variable
my_weights = tf.Variable([0.5, 0.8])

# Change the value of the variable (You cannot do this with a constant!)
my_weights.assign([0.6, 0.9])

print(my_weights)

6. Tensor Operations

TensorFlow has built-in functions for all standard mathematical operations. These operations are heavily optimized for GPU execution.
python
12345678910111213141516
tensor_a = tf.constant([1, 2, 3])
tensor_b = tf.constant([4, 5, 6])

# Addition
added = tf.add(tensor_a, tensor_b) # or simply: tensor_a + tensor_b

# Multiplication
multiplied = tf.multiply(tensor_a, tensor_b)

# Matrix Multiplication (Crucial for Neural Networks)
# Note: Matrix multiplication requires specific shapes!
mat_a = tf.constant([[1, 2], [3, 4]])
mat_b = tf.constant([[5, 6], [7, 8]])
dot_product = tf.matmul(mat_a, mat_b)

print("Dot Product:\n", dot_product)

7. Mini Project: Tensor Operations Playground

Let's generate some random tensors and inspect them, a very common task when initializing neural network weights.
python
123456789101112131415
import tensorflow as tf

# 1. Create a tensor filled with random numbers from a normal distribution
# Shape: (3, 3) - A 3x3 matrix
random_tensor = tf.random.normal(shape=(3, 3), mean=0.0, stddev=1.0)

print("Random Tensor:\n", random_tensor)

# 2. Find the maximum value in the tensor
max_val = tf.reduce_max(random_tensor)
print("\nMax Value:", max_val.numpy())

# 3. Find the index of the maximum value
max_index = tf.argmax(random_tensor[0]) # Checking the first row
print("Index of max value in row 1:", max_index.numpy())

*Notice .numpy()? If you just want the raw Python number out of a complex Tensor object, call .numpy()!*

8. The Computation Graph

Historically (in TF 1.x), you had to build a massive "Computation Graph" of operations and then "run a session" to execute it. Modern TensorFlow 2.x uses Eager Execution. This means the code runs line-by-line instantly, just like standard Python. However, behind the scenes, TensorFlow is still silently building a highly-optimized C++ graph so that when you train a model, it runs blazingly fast on the GPU.

9. Common Mistakes

  • Shape Mismatch in Matrix Multiplication: You cannot use tf.matmul on two tensors unless the inner dimensions match. E.g., A (3, 2) matrix can multiply with a (2, 5) matrix, but NOT a (3, 5) matrix. This is a strict rule of linear algebra, not just TensorFlow!
  • Mixing Data Types: Trying to add an integer tensor [1, 2] to a float tensor [1.0, 2.0] will crash. TensorFlow is strictly typed. You must cast them using tf.cast(tensor, dtype=tf.float32).

10. Best Practices

  • Use tf.float32: Deep learning relies on decimals (gradients, weights). Ensure your input tensors are usually float32. Using float64 takes up twice as much RAM on your GPU and rarely improves accuracy.

11. Exercises

  1. 1. Create a tf.constant 2D matrix filled entirely with the number 1 (Hint: research tf.ones).
  1. 2. Write code to cast an integer tensor tf.constant([10, 20]) into a float tensor.

12. MCQ Quiz with Answers

Question 1

What is the primary difference between a tf.constant and a tf.Variable?

Question 2

Why does TensorFlow use Tensors instead of standard NumPy arrays for deep learning?

13. Interview Questions

  • Q: Explain what "Rank" means in the context of a Tensor and give an example of a Rank-2 Tensor.
  • Q: Explain what an Eager Execution environment is compared to a static Graph execution environment.

14. FAQs

Q: Should I manually write tensor math for my neural networks? A: No! While understanding tensor math is important, the Keras API (tf.keras) handles all of the complex matrix multiplications and additions for you. You will rarely write raw tf.matmul code unless you are building custom, bleeding-edge architectures.

15. Summary

Tensors are the lifeblood of TensorFlow. By storing multidimensional data in these specialized objects, we unlock the ability to process massive matrices on GPU hardware and automatically calculate the calculus required for AI learning.

16. Next Chapter Recommendation

We know the theory of neural networks, and we know the data structures (Tensors) that power them. It is finally time to put it all together. In Chapter 7: Building Your First Neural Network, we will use the Keras API to build a model that can recognize handwritten numbers!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·