Your First Deep Learning Project in Python with Keras: A Step-by-Step Guide
Artificial Intelligence (AI) is transforming the world through technologies such as image recognition, speech processing, recommendation systems, and self-driving vehicles. One of the most important technologies behind these innovations is Deep Learning.
If you are interested in learning Artificial Intelligence and building your own machine learning applications, starting with a practical deep learning project is an excellent idea. Python and Keras make this process easier, even for beginners.
In this tutorial, you will learn how to create your first deep learning project using Python and Keras. We will build a simple image classification model that can recognise handwritten digits.
1. What Is Deep Learning?
Deep Learning is a branch of Machine Learning that uses artificial neural networks to learn patterns from large amounts of data. These networks are inspired by the way the human brain processes information.
Unlike traditional programming, where developers manually define rules, deep learning models learn patterns from training examples.
Deep Learning is commonly used in:
- Image and facial recognition
- Speech recognition
- Natural Language Processing (NLP)
- Medical image analysis
- Autonomous vehicles
- AI-powered recommendation systems
2. What Is Keras?
Keras is a beginner-friendly deep learning API that helps developers build, train, and test neural networks with relatively simple Python code.
Modern Keras supports multiple computational backends, including TensorFlow, JAX, and PyTorch. It provides useful tools for creating neural network architectures without writing every mathematical operation manually.
Some important features of Keras include:
- Simple and readable programming interface.
- Support for different neural network architectures.
- Tools for training and evaluating models.
- Integration with popular machine learning technologies.
- Support for GPU acceleration through compatible backends.
3. What Will We Build?
For our first project, we will develop a handwritten digit recognition system using the MNIST dataset.
The MNIST dataset contains thousands of handwritten digit images ranging from 0 to 9. Our neural network will learn to identify these digits by studying examples.
Project details:
- Programming Language: Python
- Deep Learning Library: Keras
- Dataset: MNIST
- Project Type: Image Classification
- Model: Artificial Neural Network
4. Requirements for the Project
Before starting, make sure you have access to the following tools:
- Python 3
- TensorFlow with Keras
- NumPy
- Jupyter Notebook or Google Colab
If you are a beginner, Google Colab is a convenient option because you can write and execute Python code directly in your browser without installing a complete development environment.
5. Install the Required Libraries
If you are working in a local Python environment, install TensorFlow using the following command:
pip install tensorflow numpy matplotlib
TensorFlow includes the Keras API, which we will use to develop our neural network.
6. Import the Required Libraries
The first step is importing the libraries needed for our project.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import numpy as np
Here is what each library does:
- TensorFlow: Provides the deep learning framework.
- Keras: Helps create and train neural networks.
- Matplotlib: Displays images and graphs.
- NumPy: Helps perform numerical operations.
7. Load the MNIST Dataset
Now we need data to train our model. Fortunately, Keras provides a built-in MNIST dataset, so we do not need to download it manually.
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
print("Training data:", x_train.shape)
print("Testing data:", x_test.shape)
The dataset is divided into two main sections:
- Training data: Used to teach the neural network.
- Testing data: Used to evaluate how well the trained model recognises unseen images.
The MNIST dataset contains 60,000 training images and 10,000 testing images. Each image has dimensions of 28 × 28 pixels.
8. Prepare the Dataset
Before training, we need to prepare the image data. Each pixel contains a numerical value between 0 and 255.
We will divide these values by 255 to convert them into a range between 0 and 1.
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
Normalising the data helps the neural network work with consistent numerical values during training.
9. Create Your First Neural Network
Now comes the most exciting part: building the deep learning model.
We will create a simple feedforward neural network using Keras.
model = keras.Sequential([
keras.Input(shape=(28, 28)),
layers.Flatten(),
layers.Dense(128, activation="relu"),
layers.Dense(10, activation="softmax")
])
Let's understand the different layers:
- Flatten: Converts the 28 × 28 image into a one-dimensional array.
- Dense (128): Creates a hidden layer containing 128 neurons.
- ReLU: Helps the network learn complex patterns.
- Dense (10): Produces scores for the ten possible digits (0–9).
- Softmax: Converts the output scores into probabilities.
10. Compile the Model
After creating the neural network, we need to compile it. This step defines how the model will learn and measure its performance.
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
Here is a simple explanation of these settings:
- Adam: An optimisation algorithm that updates the model's parameters during training.
- Loss Function: Measures the difference between predicted and actual results.
- Accuracy: Measures the percentage of correct predictions.
11. Train the Deep Learning Model
Now we can train our model using the training dataset.
history = model.fit(
x_train,
y_train,
epochs=5,
batch_size=32,
validation_split=0.1
)
Let's understand the training settings:
- Epochs: The number of complete passes through the training dataset.
- Batch Size: The number of training examples processed before updating the model's parameters.
- Validation Split: Uses 10% of the training data to monitor performance during training.
During training, the neural network gradually learns patterns from handwritten digit images.
12. Evaluate the Model
Once training is complete, we can evaluate the model using the testing dataset.
test_loss, test_accuracy = model.evaluate(
x_test,
y_test,
verbose=2
)
print("Test Accuracy:", test_accuracy)
The evaluation process helps us understand how well our model performs on images it did not use during training.
The actual accuracy depends on the model configuration and training process.
13. Make Your First Prediction
Let's use our trained model to predict a handwritten digit.
predictions = model.predict(x_test[:1])
predicted_digit = np.argmax(predictions[0])
print("Predicted Digit:", predicted_digit)
print("Actual Digit:", y_test[0])
plt.imshow(x_test[0], cmap="gray")
plt.title(f"Predicted: {predicted_digit}")
plt.axis("off")
plt.show()
The model will display its predicted digit alongside the original handwritten image.
If the predicted digit matches the actual digit, the model has successfully classified that example.
14. Save Your Trained Model
You do not need to train your neural network from the beginning every time. Keras allows you to save the trained model for future use.
model.save("my_first_deep_learning_model.keras")
To load the saved model later, use:
loaded_model = keras.models.load_model(
"my_first_deep_learning_model.keras"
)
This makes it easier to reuse your trained model in other Python applications.
15. What Have We Learned?
Congratulations! You have completed your first basic deep learning project using Python and Keras.
Throughout this tutorial, you have learned how to:
- Understand the fundamentals of deep learning.
- Work with Python and Keras.
- Load the MNIST dataset.
- Prepare and normalise image data.
- Build a neural network.
- Compile and train a model.
- Evaluate model performance.
- Make predictions using trained data.
- Save and reload a deep learning model.
16. What Should You Learn Next?
After completing this beginner project, you can explore more advanced deep learning concepts and develop different AI applications.
Here are some useful topics to study next:
- Convolutional Neural Networks (CNNs): Learn how neural networks analyse images.
- Recurrent Neural Networks (RNNs): Understand models designed for sequential data.
- Transfer Learning: Reuse knowledge from previously trained models.
- Natural Language Processing: Develop applications that understand human language.
- Computer Vision: Build applications that analyse visual information.
- Generative AI: Explore technologies that generate text, images, and other content.
Conclusion
Deep learning may seem complicated when you first encounter it, but starting with a small practical project makes the learning process easier. Python and Keras provide a convenient environment for understanding neural networks and developing AI applications.
By building a handwritten digit recognition system, you have explored the complete machine learning workflow, from loading data to training a neural network and making predictions.
Continue experimenting with different datasets, neural network architectures, and optimisation techniques. With regular practice, you can gradually move from beginner-level projects to more advanced artificial intelligence applications.
Frequently Asked Questions (FAQs)
1. Is Python necessary for learning deep learning?
Python is one of the most popular programming languages for deep learning because it offers powerful libraries, simple syntax, and a large developer community.
2. Is Keras suitable for beginners?
Yes. Keras provides a simple API that makes it easier to build, train, and evaluate neural networks without writing extensive low-level code.
3. What is the MNIST dataset?
MNIST is a popular dataset containing 70,000 handwritten digit images. It is frequently used for learning and experimenting with image classification.
4. Do I need a powerful computer for this project?
No. This basic MNIST project can run on an ordinary computer. You can also use Google Colab if you do not want to install Python and its libraries locally.
5. What is the difference between Machine Learning and Deep Learning?
Machine Learning includes different techniques that allow computers to learn from data. Deep Learning is a specialised branch of Machine Learning that uses multi-layer neural networks.
6. Can I use Keras for real-world AI projects?
Yes. Keras can be used to develop image classification, text processing, prediction, and other deep learning applications.