DEV Community

Cover image for TensorFlow Made Simple: Your First Step into Machine Learning
Jay Codes
Jay Codes

Posted on

TensorFlow Made Simple: Your First Step into Machine Learning

1. What is TensorFlow?

1.1. A brief overview of TensorFlow and its capabilities.

TensorFlow, developed by Google, is an open-source machine learning framework that has gained immense popularity in the artificial intelligence community. Its name "TensorFlow" stems from the mathematical term "tensor," which refers to a multi-dimensional array. In TensorFlow, data is represented as tensors, making it an efficient tool for handling complex mathematical operations and data manipulations intrinsic to machine learning algorithms.

Imagine TensorFlow as a sophisticated calculator that can handle vast datasets and perform intricate calculations with ease. This powerful framework provides developers with a robust foundation for creating, training, and deploying machine learning models across diverse applications and industries.

1.2. Advantages of using TensorFlow for machine learning projects.

TensorFlow offers numerous advantages that have contributed to its widespread adoption in the machine learning community:

  • Scalability: One of TensorFlow's key strengths is its ability to distribute computations across multiple CPUs and GPUs, making it suitable for large-scale projects and production environments. This enables data scientists and engineers to leverage the full potential of modern hardware.

  • Flexibility: TensorFlow supports a wide variety of neural network architectures and model types, ranging from simple linear regression to complex deep learning models. This flexibility empowers developers to tackle diverse machine learning tasks, from image recognition and natural language processing to reinforcement learning.

  • Community and Ecosystem: TensorFlow boasts a thriving and active community of developers and researchers who actively contribute to its growth. As a result, users can access a wealth of pre-trained models, libraries, and tools, allowing them to accelerate their development process and experiment with cutting-edge techniques.

  • TensorBoard: TensorFlow comes bundled with TensorBoard, a powerful visualization tool that aids in monitoring and understanding models during training. With TensorBoard, users can track metrics, visualize computational graphs, and inspect model behavior, enabling more informed decisions in model optimization.

1.3. Components of TensorFlow (Graph and Session)

TensorFlow's underlying architecture is organized as a directed acyclic graph (DAG) known as the computational graph. This graph represents the sequence of mathematical operations that TensorFlow performs to execute a machine learning task. However, constructing this graph is handled automatically by TensorFlow, and users typically don't need to interact with it directly.

Once the computational graph is defined, it needs to be executed within a session. The session is responsible for running the operations defined in the graph. In essence, you can think of the computational graph as a detailed recipe, while the session serves as the chef who follows the recipe to prepare the desired dish.

The separation of graph definition and execution allows TensorFlow to optimize the computation, making it more efficient and scalable.

2. Setting up Google Colaboratory

2.1. Introduction to Google Colaboratory (Colab) as a cloud-based IDE

Google Colaboratory, or Colab, is a free cloud-based Integrated Development Environment (IDE) provided by Google. It allows developers to write and execute Python code in their web browsers, making it a convenient choice for running TensorFlow without the need for local installations or expensive hardware.

The collaborative nature of Colab enables teams to work together on machine learning projects in real-time, fostering collaboration and knowledge sharing.

2.2. How to access and create a new Colab notebook

Accessing Google Colab is simple. Open your web browser and navigate to Google Colaboratory. If you have a Google account, sign in and create a new Colab notebook by clicking "New Notebook" in the "File" menu.

Google Colab Interface

Once inside a Colab notebook, you can execute code cells individually, making it easy to experiment with TensorFlow without worrying about the environment setup.

Google Colab
Click on "Code" or "Text" to either add a code or a text block.

The reason I prefer to use Google Colab Is because of its simplicity and it already has so many libraries pre-installed since it's a cloud-based IDE

2.3. Importing TensorFlow in Colab and checking for GPU/TPU availability

As mentioned earlier, TensorFlow is pre-installed in Colab, but since we're using Colab we need to specify which version we want it to import:

%tensorflow_version 2.x
Enter fullscreen mode Exit fullscreen mode

Now you can directly import it using the following Python code:

import tensorflow as tf
Enter fullscreen mode Exit fullscreen mode

Remember if you're not using the Google colaboratory you'd have to install Python and TensorFlow on your local machine.

Now, let's check whether your Colab instance has access to a Graphics Processing Unit (GPU) or a Tensor Processing Unit (TPU). These hardware accelerators can significantly speed up the training of large models.

print("GPU Available:", tf.test.is_gpu_available())
print("TPU Available:", "Yes" if "COLAB_TPU_ADDR" in os.environ else "No")
Enter fullscreen mode Exit fullscreen mode

If your Colab environment has access to a GPU or TPU, you'll see "GPU Available: True" or "TPU Available: Yes," respectively. Otherwise, it will show "False" or "No."

3. Creating Tensors

3.1. Understanding the Fundamental Building Blocks of TensorFlow: Tensors

In TensorFlow, data is represented as tensors. You can think of a tensor as a multi-dimensional array with a uniform data type. Tensors are similar to NumPy arrays, but they have an advantage: they can be operated on both CPUs and GPUs, providing accelerated computation for machine learning tasks.

To illustrate this concept, let's consider a grayscale image of dimensions 100x100 pixels. In NumPy, you'd represent this image as a 2D array, and manipulating it with standard Python code can be slow for large images. TensorFlow, on the other hand, can perform operations on this image using specialized algorithms, which are significantly faster.

3.2. Rank/Degree of tensors

Tensors have a property called rank, also known as degree, which refers to the number of dimensions they have. Understanding the rank of a tensor is crucial because it determines how we access and manipulate its data.

Let's explore different ranks of tensors with examples:

# Rank 0: Scalar
scalar = tf.constant(5)

# Rank 1: Vector
vector = tf.constant([1, 2, 3])

# Rank 2: Matrix
matrix = tf.constant([[1, 2, 3], [4, 5, 6]])

# Rank 3: 3-dimensional tensor
tensor_3d = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
Enter fullscreen mode Exit fullscreen mode

The scalar has rank 0, the vector has rank 1, the matrix has rank 2, and the 3-dimensional tensor has rank 3. You can think of the rank as the number of indices required to access a specific element within the tensor.

3.3. Shapes of tensors

The shape of a tensor specifies the number of elements it contains along each dimension. The shape is crucial because it determines how tensors can be combined, transformed, and used in operations.

Let's explore different shapes of tensors with examples:

# Shape (2,) -> A vector with 2 elements
vector = tf.constant([1, 2])

# Shape (2, 3) -> A matrix with 2 rows and 3 columns
matrix = tf.constant([[1, 2, 3], [4, 5, 6]])

# Shape (2, 2, 2) -> A 3-dimensional tensor with a shape of 2x2x2
tensor_3d = tf.constant([

[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
Enter fullscreen mode Exit fullscreen mode

3.4. Reshaping tensors

You can reshape tensors to change their dimensions while keeping the same number of elements. Reshaping is a powerful technique that enables you to convert data into formats suitable for specific machine learning models.

Let's see an example:

# Reshape a tensor of shape (2, 2) into shape (4,)
matrix = tf.constant([[1, 2], [3, 4]])
reshaped_matrix = tf.reshape(matrix, [4])
Enter fullscreen mode Exit fullscreen mode

Reshaping can be particularly useful when you want to flatten a matrix into a vector or when you need to transform data to feed it into a neural network.

3.5. Using TensorFlow to create and manipulate tensors in Colab

Now that we have a good understanding of the basics of tensors, let's use TensorFlow to create and manipulate tensors in Colab. We can perform various mathematical operations, apply functions, and much more.

# Create tensors
tensor_a = tf.constant([1, 2, 3])
tensor_b = tf.constant([4, 5, 6])

# Addition
sum_tensor = tf.add(tensor_a, tensor_b)

# Element-wise multiplication
product_tensor = tf.multiply(tensor_a, tensor_b)

# Matrix multiplication
matrix_a = tf.constant([[1, 2], [3, 4]])
matrix_b = tf.constant([[5, 6], [7, 8]])
matrix_product = tf.matmul(matrix_a, matrix_b)
Enter fullscreen mode Exit fullscreen mode

Let's see the outcomes of the code snippets:

print("Sum Tensor:", sum_tensor.numpy())  # Output: [5 7 9]
print("Product Tensor:", product_tensor.numpy())  # Output: [4 10 18]
print("Matrix Product:", matrix_product.numpy())  # Output: [[19 22] [43 50]]
Enter fullscreen mode Exit fullscreen mode

By combining tensors with various operations, you can build complex machine learning models and perform intricate computations with ease.

3.6. Exploring different types of tensors: constants, variables, and placeholders

In TensorFlow, there are three main types of tensors: constants, variables, and placeholders.

Constants hold values that do not change during computation. They are useful for defining model parameters and hyperparameters that remain constant throughout training.

Variables are used to represent values that can be updated during training. For instance, the weights and biases in a neural network are typically represented as variables.

Placeholders serve as input nodes to the computational graph. They allow you to feed data into the graph during a session. Placeholders are commonly used to provide training data in batches to a machine learning model.

# Constants
const_tensor = tf.constant([1, 2, 3])

# Variables
variable_tensor = tf.Variable([4, 5, 6])

# Placeholders (defining a placeholder with shape=None allows it to accept tensors of different sizes)
placeholder_tensor = tf.placeholder(tf.float32, shape=None)
Enter fullscreen mode Exit fullscreen mode

By utilizing these different types of tensors, you can build and train complex machine learning models with ease.


In this article, we introduced TensorFlow, a powerful open-source machine learning framework developed by Google. We explored its capabilities, including its scalability, flexibility, and rich ecosystem. TensorFlow's computational graph and session enable efficient execution of machine learning tasks, making it a versatile tool for developers and researchers alike.

We also discussed how to set up Google Colaboratory (Colab), a cloud-based IDE that allows us to experiment with TensorFlow in a collaborative environment without any local installations.

Furthermore, we delved into the fundamentals of TensorFlow tensors, including their rank, shape, and the various types of tensors: constants, variables, and placeholders. Understanding these concepts is essential for building and training machine learning models effectively.

As you continue your journey with TensorFlow, remember to leverage its extensive documentation, tutorials, and the active community to further enhance your skills and explore the vast possibilities that machine learning has to offer.

Happy learning and building with TensorFlow!

Top comments (0)