Keras Python Example: Build Your First Neural Network in Minutes

Logan Jul 13, 2026

Welcome to the world of deep learning with Python! Keras, a user-friendly, modular, and extensible neural network library, is a popular choice for developers looking to leverage the power of machine learning in their applications. In this guide, we'll explore a comprehensive Keras Python example, diving into its fundamental aspects and practical usage.

Time Series Analysis with LSTM using Python's Keras Library
Time Series Analysis with LSTM using Python's Keras Library

Keras, initially developed by François Chollet in 2015, is built on TensorFlow and designed to enable fast experimentation and easy prototyping. It упрощает creation, training, and evaluation of neural networks, making it a great choice for both beginners and seasoned data scientists.

Traffic Signs Recognition using CNN and Keras in Python
Traffic Signs Recognition using CNN and Keras in Python

Keras Basics and Installation

To begin our Keras Python example, let's first ensure you have the necessary libraries installed. Keras is typically installed via pip:

Image Classification using Deep Learning
Image Classification using Deep Learning

pip install keras

Or, if you're using TensorFlow 2.x, you can import Keras directly from TensorFlow:

Deep Learning with Keras: Implementing deep learning models and neural networks with the power of Python
Deep Learning with Keras: Implementing deep learning models and neural networks with the power of Python

import tensorflow as tf from tensorflow import keras

Importing Keras

Once installed, importing Keras is straightforward:

All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)

from keras import models, layers

Or, with TensorFlow 2.x:

from tensorflow.keras.models import Sequential

three different types of python programming
three different types of python programming

Building Your First Model

Let's create a simple model using Keras' Sequential API, which is well-suited for linear stacks of layers:

a poster showing the different types of people
a poster showing the different types of people
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)
Python Kivy Projects
Python Kivy Projects
Different Types of Variables in Python with Examples
Different Types of Variables in Python with Examples
Python Programming Language Guide, Learn Python For Science Students, Python Programming For Science, Programming Projects, Learn Python, Learn Python In One Picture, Python Learning, Python Aesthetic, Python Projects
Python Programming Language Guide, Learn Python For Science Students, Python Programming For Science, Programming Projects, Learn Python, Learn Python In One Picture, Python Learning, Python Aesthetic, Python Projects
Python Learning Path for Beginners 2026 🚀
Python Learning Path for Beginners 2026 🚀
What is Clustering & its Types? K-Means Clustering Example (Python)
What is Clustering & its Types? K-Means Clustering Example (Python)
30-Day Python Learning Plan for Beginners | Complete Python Roadmap to Learn Coding Fast
30-Day Python Learning Plan for Beginners | Complete Python Roadmap to Learn Coding Fast
Python Beginner Roadmap 2026: Learn Python Step-by-Step From Zero to Job Ready
Python Beginner Roadmap 2026: Learn Python Step-by-Step From Zero to Job Ready

model = keras.models.Sequential()

To add layers, use the add() method:

model.add(keras.layers.Dense(32, activation="relu", input_shape=(28, 28)))

For more complex architectures, consider using the functional API or Model subclassing.

Datasets and Loading Data

Keras provides several utility modules for working with datasets, such as keras.datasets and keras.preprocessing. For instance, let's load the classic MNIST dataset:

from keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

Data Preprocessing

Before creating our model, we need to preprocess the data:

x_train = x_train.reshape(-1, 28 * 28) / 255.0

Using numpy or pandas for data manipulation is common in Keras workflows. Keep in mind that preprocessing steps should be done in a way that allows for reproducible results when feeding data to the model.

Data Augmentation

Keras' ImageDataGenerator facilitates data augmentation, which can help improve model performance, especially on small datasets:

from keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(rotation_range=10, zoom_range=0.1)

Use the flow() method to generate batches of augmented images during training:

datagen.flow(x_train, y_train, batch_size=32)

oue Keras Python Example: Building and Training a Network

Now we'll create and train a simple artificial neural network (ANN) on the MNIST dataset:

from keras.models import Sequential

model = Sequential()

model.add(layers.Dense(64, activation='relu', input_shape=(28 * 28,)))

model.add(layers.Dense(64, activation='relu'))

model.add(layers.Dense(10, activation='softmax'))

Compile the model with an appropriate optimizer and loss function:

model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

Finally, train the model on the data:

history = model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))

Evaluating the Model

After training, evaluate the model's performance using the test data:

test_loss, test_accuracy = model.evaluate(x_test, y_test)

Plot the training and validation accuracy and loss over epochs using matplotlib to visualize performance:

import matplotlib.pyplot as plt

history_dict = history.history

plt.plot(history_dict['accuracy'], label='accuracy')

plt.plot(history_dict['val_accuracy'], label='val_accuracy')

Keras offers a wide range of capabilities, including support for different architectures, data types, and algoritms, as well as seamless integration with popular libraries like TensorFlow, Theano, and PlaidML. We encourage you to explore these features to build robust, efficient, and performant machine learning models in Python.