You are currently viewing Introduction to Deep Learning with Keras in Python

Introduction to Deep Learning with Keras in Python

  • Post author:
  • Post category:Python
  • Post comments:0 Comments
  • Post last modified:February 23, 2024

In this tutorial, we will introduce you to the world of deep learning using Python and Keras. Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. It is designed to enable fast experimentation with deep neural networks.

We’ll cover the following topics:

  1. Installation
  2. Basics of Keras
  3. Building a Neural Network with Keras
  4. Training the Model
  5. Evaluating the Model
  6. Saving and Loading Models
  7. Example: Image Classification with Keras (MNIST dataset)

1. Installation

Before we get started, you’ll need to have Python installed on your system. You can install Keras and TensorFlow using pip, which is Python’s package installer:

pip install keras tensorflow

This will install both Keras and TensorFlow, which Keras uses as its backend.

2. Basics of Keras

Keras provides a simple and intuitive interface for creating neural networks. The core data structure of Keras is a model, a way to organize layers. The main type of model is the Sequential model, a linear stack of layers.

from keras.models import Sequential
from keras.layers import Dense

# Create a Sequential model
model = Sequential()

# Add layers to the model
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))

3. Building a Neural Network with Keras

Let’s create a simple neural network for binary classification:

from keras.models import Sequential
from keras.layers import Dense

# Create a Sequential model
model = Sequential()

# Add layers to the model
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))

# Compile the model
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

4. Training the Model

To train the model, we need some data. We’ll use random data for this example:

import numpy as np

# Generate random data
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))

# Split the data into training and testing sets
train_data = data[:800]
train_labels = labels[:800]
test_data = data[800:]
test_labels = labels[800:]

# Train the model
model.fit(train_data, train_labels, epochs=10, batch_size=32)

5. Evaluating the Model

After training, we can evaluate the model on the test data:

# Evaluate the model
loss, accuracy = model.evaluate(test_data, test_labels)
print(f'Accuracy: {accuracy}')

6. Saving and Loading Models

You can save the trained model to a file and load it later:

# Save the model
model.save('model.h5')

# Load the model
from keras.models import load_model
loaded_model = load_model('model.h5')

7. Example: Image Classification with Keras (MNIST dataset)

Now let’s do a more practical example using the MNIST dataset for image classification:

from keras.datasets import mnist
from keras.utils import to_categorical

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

# Preprocess the data
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255

test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

# Build the model
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(28 * 28,)))
model.add(Dense(10, activation='softmax'))

model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# Train the model
model.fit(train_images, train_labels, epochs=5, batch_size=128)

# Evaluate the model
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)

This example builds a neural network for recognizing handwritten digits from the MNIST dataset.

This concludes our tutorial on getting started with Python and Keras for deep learning. Experiment with different architectures, datasets, and parameters to get a better understanding of how neural networks work and how to use Keras effectively.

Leave a Reply