Last modified: Dec 28, 2025 By Alexander Williams

Intro to Deep Learning with TensorFlow Keras

Deep learning is a key part of modern AI. It powers many technologies we use daily. This guide introduces you to its core concepts.

We will use TensorFlow and Keras. These are powerful Python libraries. They make building neural networks much simpler.

This article is for beginners. No prior deep learning knowledge is needed. Basic Python skills are helpful.

What is Deep Learning?

Deep learning is a type of machine learning. It uses artificial neural networks. These networks have many layers.

The "deep" refers to these multiple layers. Each layer learns different features from data. This allows for complex pattern recognition.

It excels in tasks like image and speech recognition. It also powers natural language processing and more.

Why TensorFlow and Keras?

TensorFlow is an open-source library from Google. It is designed for numerical computation. It is perfect for machine learning.

Keras is a high-level neural networks API. It runs on top of TensorFlow. It provides a simpler, more intuitive interface.

Together, they offer a great balance. You get Keras's ease of use with TensorFlow's power. This speeds up development and prototyping.

Setting Up Your Environment

First, you need to install the libraries. Use pip, the Python package installer. Run the command below in your terminal.


pip install tensorflow

This installs TensorFlow and the built-in Keras. Verify the installation by importing them in Python.


import tensorflow as tf
from tensorflow import keras
print("TensorFlow version:", tf.__version__)
print("Keras version:", keras.__version__)

TensorFlow version: 2.15.0
Keras version: 2.15.0

Good data is the foundation of any model. Before building, perform Exploratory Data Analysis Python Guide & Techniques. This helps you understand your dataset's patterns.

Core Concepts: Tensors and Layers

Tensors are the basic data structure. They are multi-dimensional arrays. Think of them as generalized matrices.

Layers are the building blocks of neural networks. Each layer performs a specific transformation on its input. Keras provides many pre-built layers.

A model is a sequence of layers. It defines the network's architecture. The keras.Sequential model is the simplest.

Building Your First Neural Network

Let's create a model for a simple classification task. We'll use the famous MNIST dataset of handwritten digits.

First, load and prepare the data. The data needs to be normalized for better training.


# Load the MNIST dataset
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# Normalize pixel values to be between 0 and 1
train_images = train_images / 255.0
test_images = test_images / 255.0

Now, define the model architecture. We use a Sequential model with three layers.


model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),  # Flattens 28x28 image to a 784 vector
    keras.layers.Dense(128, activation='relu'), # A dense layer with 128 neurons
    keras.layers.Dense(10, activation='softmax') # Output layer for 10 digit classes
])

The Flatten layer transforms the 2D image. The Dense layers are fully connected. The last layer uses softmax for probability scores.

Compiling the Model

Before training, you must compile the model. This configures the learning process.

You specify an optimizer, a loss function, and metrics. The optimizer adjusts the model's weights. Loss measures the model's error.


model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

Here, we use the 'adam' optimizer. It is efficient and popular. The loss is for multi-class classification.

Training the Model

Training is done with the fit method. You pass the training data and labels. You also set the number of epochs.

An epoch is one full pass through the training data. We will train for 5 epochs.


history = model.fit(train_images, train_labels, epochs=5)

Epoch 1/5
1875/1875 [==============================] - 5s 2ms/step - loss: 0.2587 - accuracy: 0.9265
Epoch 2/5
1875/1875 [==============================] - 4s 2ms/step - loss: 0.1136 - accuracy: 0.9666
Epoch 3/5
1875/1875 [==============================] - 4s 2ms/step - loss: 0.0776 - accuracy: 0.9765
Epoch 4/5
1875/1875 [==============================] - 4s 2ms/step - loss: 0.0586 - accuracy: 0.9821
Epoch 5/5
1875/1875 [==============================] - 4s 2ms/step - loss: 0.0452 - accuracy: 0.9860

The accuracy improves with each epoch. The loss decreases. This shows the model is learning.

Often, your data comes from various sources like spreadsheets. Tools like Integrate Python xlrd with pandas for Data Analysis are crucial for data preparation.

Evaluating Model Performance

After training, evaluate on unseen test data. Use the evaluate method.


test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

313/313 - 1s - loss: 0.0767 - accuracy: 0.9761
Test accuracy: 0.9761000275611877

The test accuracy is about 97.6%. This is good for a first model. It generalizes well to new data.

Making Predictions

Use the trained model to make predictions. Call the predict method on new data.


predictions = model.predict(test_images)
# Let's look at the prediction for the first test image
print(predictions[0])
print("Predicted class:", predictions[0].argmax())
print("True class:", test_labels[0])

[1.0541915e-08 1.6930135e-07 1.1743555e-05 1.9964113e-04 1.0541915e-08
 1.0541915e-08 1.0541915e-08 9.9977591e-01 1.0541915e-08 1.0541915e-08]
Predicted class: 7
True class: 7

The output is a probability distribution. The highest probability is at index 7. The model correctly predicts the digit 7.

Managing and cleaning data is a key step. A Master Data Analysis with Pandas Python Guide is an essential skill for any data scientist.

Key Takeaways and Next Steps

You built and trained a neural network. You learned the basic workflow with Keras.

Always start with simple models. Then gradually increase complexity. This helps with debugging and understanding.

Experiment with different architectures. Try more layers or different activations. Also, try different datasets.

Conclusion

Deep learning is accessible with TensorFlow and Keras. This guide covered the essential first steps.

You learned to load data, build a model, and train it. You also evaluated its performance and made predictions.

The field is vast and exciting. Continue learning about convolutional and recurrent networks. Happy coding!