Keras Tutorial for Python Deep Learning

Keras is a Python library for building, training, evaluating, and deploying machine-learning models. Its high-level API provides layers, models, optimizers, losses, metrics, callbacks, and data-processing utilities for common deep-learning workflows.

This Keras tutorial explains the library’s role, its relationship with TensorFlow, installation options, the Sequential model, Dense layers, model compilation, training, evaluation, and prediction. It also updates the original binary-classification example with a separate test set and current Keras APIs.

About the Keras Deep Learning Library

Keras is a python deep learning library. The main focus of Keras library is to aid fast prototyping and experimentation. It helps researchers to bring their ideas to life in least possible time.

A Keras model is assembled from reusable components. Layers transform tensors, a loss function measures prediction error, an optimizer updates trainable parameters, and metrics report selected aspects of model performance. Models can be created with the Sequential API, Functional API, or model subclassing.

Keras Sequential, Functional, and Subclassing APIs

Keras APISuitable model structureTypical use
Sequential APIA single linear stack of layersSimple classifiers and regressors in which each layer has one input and one output
Functional APIGraphs with branches, shared layers, or multiple inputs and outputsModels that cannot be represented as one linear stack
Model subclassingCustom computation controlled through Python codeResearch models and architectures requiring specialized forward-pass logic

The Sequential API is used in this tutorial because the example consists of a straightforward stack of fully connected layers.

Keras and TensorFlow Backend Relationship

Keras does not replace any of TensorFlow (by Google), CNTK (by Microsoft) or Theano but instead it works on top of them. Infact, Keras needs any of these backend deep-learning engines, but Keras officially recommends TensorFlow.

The paragraph above describes the older Keras 2 architecture. Current Keras releases use a multi-backend design and can run with supported TensorFlow, JAX, or PyTorch backends. CNTK and Theano are no longer current Keras backends. TensorFlow also exposes the Keras API through tf.keras.

Examples in this page use standalone imports such as import keras and from keras.models import Sequential. In an existing TensorFlow project, equivalent components may be imported consistently from tensorflow.keras. Avoid mixing standalone keras and tensorflow.keras objects within the same model unless the installed versions are known to be compatible.

Keras and Python Version Compatibility

Keras is compatible with Python2 (starting from v2.7) and Python3 (till version 3.6).

That compatibility statement applies only to historical Keras releases. Current Keras development targets supported Python 3 versions; Python 2 is no longer supported. Check the requirements for the specific Keras release and selected backend before creating the environment because supported Python, accelerator, and operating-system combinations change over time.

Features of the Keras Python Library

  1. Keras is an user friendly API. It has consistent and simple APIs. For regular use cases, it requires very less of user effort.
  2. Keras gives a very useful feedback about user actions in case of any error. It provides with the actionable feedback which helps developers to pinpoint the line or error and correct it.
  3. Keras does not require separate configuration files for models. You can describe the model configuration in Python code itself.
  4. Keras can run seamlessly on both CPU and GPU with required libraries installed.
  5. Keras is extensible, which means you can add new modules as new classes and functions.
  6. When it comes to support for development with Keras Library, Keras provides good number of examples for the existing models.

In practical projects, Keras also provides utilities for saving models, loading trained models, preprocessing data, controlling training with callbacks, and defining custom layers, losses, metrics, and training behavior.

Install Keras with a TensorFlow Backend

With this little introduction to Keras, let us now get started with development using Keras library.

Lets not complicate any of the configurations and take things smoothly. To do that, we shall install TensorFlow first, because Keras will use TensorFlow, by default, as its tensor manipulation library.

To install TensorFlow on your machine, go to https://www.tensorflow.org/versions/ and click on the latest stable release available. In the left menu, you will see a link for installation steps. Example url would be https://www.tensorflow.org/versions/r1.9/install/. Identify your OS and follow the respective steps.

The second link above is retained as a reference to the TensorFlow 1.9 instructions used by the original tutorial. For a new environment, use installation instructions for the current TensorFlow and Keras releases rather than TensorFlow 1.x commands.

Or if you have pip already installed, just run the following command :

$ sudo pip install tensorflow

With TensorFlow installed, now its time to install Keras.

Install Keras from PyPI (recommended)

$ sudo pip install keras

If you are using a virtualenv, you may want to avoid using sudo:

$ pip install keras

If you would like experiment with the latest Keras code available there, clone Keras using Git

$ git clone https://github.com/keras-team/keras.git

and install it using python

$ cd keras
$ sudo python setup.py install

The commands above are preserved from the original tutorial, but system-wide sudo pip installations and setup.py install are not recommended for a new project. Create an isolated environment and invoke pip through the environment’s Python interpreter instead.

</>
Copy
python -m venv .venv

# Linux or macOS
source .venv/bin/activate

# Windows Command Prompt
# .venv\Scripts\activate

python -m pip install --upgrade pip
python -m pip install keras tensorflow

Verify which Keras version and backend are active before running a model.

</>
Copy
import keras

print("Keras version:", keras.__version__)
print("Keras backend:", keras.backend.backend())

Select a Keras Backend Before Importing Keras

When a project uses standalone multi-backend Keras, the backend can be selected with the KERAS_BACKEND environment variable. Set it before importing Keras. The required backend package must also be installed.

</>
Copy
import os

os.environ["KERAS_BACKEND"] = "tensorflow"

import keras
print(keras.backend.backend())

Use one backend consistently for the project. A backend change may require restarting the Python process or notebook kernel because Keras is initialized when it is imported.

Basic Binary Classification Example Using Keras

The following example demonstrates the main Keras workflow: load numeric data, separate features and labels, create a neural network, configure its training behavior, fit it, and evaluate it. The dataset has eight input columns and one binary target column.

Import Keras Sequential and Dense Classes

Sequential() is a simple model available in Keras. It adds layers one on another sequentially, hence Sequential model. For layers we use Dense() which takes number of nodes and activation type.

</>
Copy
from keras.models import Sequential
from keras.layers import Dense

A Dense layer connects every input from the previous layer to every unit in the current layer. The activation argument specifies the function applied to the layer’s output.

Load the CSV Dataset for Keras

We shall consider a csv file as dataset. Following is a sample of it containing three observations.

6,148,72,35,0,33.6,0.627,50,1
1,85,66,29,0,26.6,0.351,31,0
8,183,64,0,0,23.3,0.672,32,1

First eight columns are features of an experiment while the last(ninth) column is output label.

You can download the dataset from here.

</>
Copy
import numpy

# load dataset
dataset = numpy.loadtxt("input-data.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

In this example, we shall train a binary classifier. Output labels are either 1 or 0.

Before training, confirm that every row has nine numeric values, missing values have been handled appropriately, and the final column contains the intended labels. The downloaded data should also be reviewed for its source, permitted use, and suitability before it is used beyond this programming demonstration.

Build the Keras Sequential Model

Now, we define model using Keras Sequential() and Dense() classes.

</>
Copy
model = Sequential()
model.add(Dense(10, input_dim=8, activation='relu'))
model.add(Dense(5, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

The code is simple and easy to read. We created a Sequential() model and added three Dense() layers to it. The first Dense layer consists of 10 nodes, each node receives input from eight input nodes and the activation used for the node is relu (rectified linear unit). The second layer has 5 nodes and the activation function used is relu. The third layer is our output node and has only one node, whose activation is sigmoid, to output 1 or 0. So, apart from input and output, we have two layers in between them. You can add some more layers in between with different activation layers. The selection has to be done by considering type of data, and can also be done on a trail and error basis.

More precisely, the model contains two hidden Dense layers followed by one output layer. The sigmoid output is suitable for estimating a probability for a binary target. Adding layers or units should be guided by validation performance and the characteristics of the problem, not by training accuracy alone.

In current Keras code, an explicit Input object is generally clearer than passing input_dim to the first Dense layer.

</>
Copy
import keras
from keras import layers

model = keras.Sequential([
    keras.Input(shape=(8,)),
    layers.Dense(10, activation="relu"),
    layers.Dense(5, activation="relu"),
    layers.Dense(1, activation="sigmoid"),
])

Compile and Fit the Keras Model

During compilation, we specify how the error has to calculated and what type of optimizer has to be used to reduce that error, and what are the metrics we are interested in.

Fitting builds the compiled model with the dataset. During fitting, we specify the number of epochs (number of reruns on the dataset) and batch_size.

</>
Copy
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit the model
model.fit(X, Y, epochs=150, batch_size=10)

Fitting the model takes some time. 150 Epochs has to be completed and once done, our model is trained and ready.

Each epoch is one pass through the training data, and batch_size=10 requests parameter updates based on batches of up to ten samples. The appropriate epoch count depends on the dataset and model. Monitor validation metrics and consider early stopping instead of assuming that 150 epochs is always suitable.

Evaluate Keras Binary Classification Accuracy

We can evaluate the build model.

</>
Copy
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

During model compilation, we added accuracy as a metric, along with the default loss metric.

This original example evaluates the model on the same observations used for training. Its result describes performance on those training observations and should not be treated as an estimate of performance on unseen data. Use separate training, validation, and test data for a meaningful evaluation.

Complete Python Program – Keras Binary Classifier

Consolidating all the above steps, we get the following python program.

Python Program

</>
Copy
from keras.models import Sequential
from keras.layers import Dense
import numpy
# fix random seed for reproducibility
numpy.random.seed(7)
print('random seed set')

# load dataset
dataset = numpy.loadtxt("input-data.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
print('input data loaded')

# create model
model = Sequential()
model.add(Dense(10, input_dim=8, activation='relu'))
model.add(Dense(5, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
print('model created')

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

# Fit the model
model.fit(X, Y, epochs=150, batch_size=10)
print('data fit to model')

# evaluate the model
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

Updated Keras Classifier with Training and Test Data

The following version keeps test rows separate, adapts feature normalization using training data only, uses an explicit input shape, and evaluates the trained model on unseen test rows. The random shuffle makes the split reproducible for this example.

</>
Copy
import numpy as np
import keras
from keras import layers

keras.utils.set_random_seed(7)

# Load nine numeric columns: eight features and one binary label.
data = np.loadtxt("input-data.csv", delimiter=",", dtype="float32")
X = data[:, :8]
y = data[:, 8]

# Shuffle before taking a simple 80/20 split.
indices = np.random.permutation(len(X))
X = X[indices]
y = y[indices]

split_index = int(len(X) * 0.8)
X_train, X_test = X[:split_index], X[split_index:]
y_train, y_test = y[:split_index], y[split_index:]

# Learn normalization statistics from training features only.
normalizer = layers.Normalization()
normalizer.adapt(X_train)

model = keras.Sequential([
    keras.Input(shape=(8,)),
    normalizer,
    layers.Dense(10, activation="relu"),
    layers.Dense(5, activation="relu"),
    layers.Dense(1, activation="sigmoid"),
])

model.compile(
    optimizer="adam",
    loss="binary_crossentropy",
    metrics=["accuracy"],
)

callbacks = [
    keras.callbacks.EarlyStopping(
        monitor="val_loss",
        patience=10,
        restore_best_weights=True,
    )
]

model.fit(
    X_train,
    y_train,
    validation_split=0.2,
    epochs=150,
    batch_size=10,
    callbacks=callbacks,
    verbose=1,
)

test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"Test loss: {test_loss:.4f}")
print(f"Test accuracy: {test_accuracy:.4f}")

A random holdout is suitable for demonstrating the API, but the correct splitting method depends on the data. Time-ordered records, grouped observations, and imbalanced labels may require chronological, group-aware, or stratified splitting to prevent leakage and misleading measurements.

Generate Predictions with the Trained Keras Model

For a sigmoid binary classifier, model.predict() returns probability-like scores. Apply a decision threshold to convert those scores into class labels.

</>
Copy
probabilities = model.predict(X_test, verbose=0).reshape(-1)
predicted_classes = (probabilities >= 0.5).astype("int32")

for probability, predicted_class in zip(
    probabilities[:5], predicted_classes[:5]
):
    print(f"probability={probability:.4f}, class={predicted_class}")

A threshold of 0.5 is a conventional starting point, not a rule for every application. Select the decision threshold using validation data and metrics that reflect the costs of false positives and false negatives.

Save and Reload a Keras Model

Save the trained model when it needs to be reused without training it again. The native .keras format stores the model configuration and learned weights, along with compile information when available.

</>
Copy
model.save("binary_classifier.keras")

restored_model = keras.models.load_model("binary_classifier.keras")
restored_loss, restored_accuracy = restored_model.evaluate(
    X_test, y_test, verbose=0
)

print(f"Restored test accuracy: {restored_accuracy:.4f}")

Common Keras Installation and Training Problems

Keras import fails after installation

Confirm that Keras and its backend were installed into the same environment used to run the script. Commands such as python -m pip show keras help avoid confusion when several Python installations are present.

Keras reports that no backend is available

Install a supported backend and configure the intended backend before importing Keras. Restart the interpreter after changing backend configuration.

Keras input shape does not match the CSV data

The example expects each input row to contain eight features, so the model input shape is (8,). Inspect X.shape and verify the selected columns when Keras reports an incompatible shape.

Keras training accuracy is high but test accuracy is low

This pattern can indicate overfitting, an unrepresentative split, or data leakage. Review the split first, then consider fewer model parameters, better data, appropriate regularization, and early stopping.

Keras Python Tutorial FAQs

What is Keras used for in Python?

Keras is used to define, train, evaluate, save, and deploy machine-learning models. It includes APIs for neural-network layers as well as supporting components such as optimizers, losses, metrics, callbacks, and data utilities.

What is the difference between Keras and TensorFlow?

Keras is a high-level modeling API, while TensorFlow is a broader numerical computing and machine-learning platform that can serve as a Keras backend. TensorFlow also makes the Keras API available through tf.keras.

Should Python code import keras or tensorflow.keras?

Use keras for a standalone Keras project, particularly when the multi-backend API is required. Use tensorflow.keras when working within a TensorFlow-specific codebase. Keep the chosen import style consistent throughout the model.

Why is a Keras model evaluated on separate test data?

Evaluation on unseen test data provides a better indication of how the selected model performs beyond its training observations. Measuring only the training data can conceal overfitting.

When should the Keras Functional API be used instead of Sequential?

Use the Functional API when a model has multiple inputs or outputs, shared layers, residual connections, or branches. Sequential is intended for one linear stack of layers.

Keras Tutorial Editorial QA Checklist

  • Confirm that installation guidance distinguishes current Keras releases from historical Keras 2 and TensorFlow 1.x instructions.
  • Verify that standalone keras and tensorflow.keras imports are not mixed within one model example.
  • Confirm that the selected Keras backend is installed and configured before Keras is imported.
  • Verify that the model input shape matches the eight feature columns in the CSV file.
  • Ensure normalization or other learned preprocessing is adapted only on training data.
  • Keep training, validation, and test roles separate when reporting model performance.
  • Describe sigmoid predictions as scores and state the threshold used to create binary labels.
  • Check that claims about Python, Keras, backend, GPU, and operating-system compatibility match the versions being documented.

Keras Binary Classifier Tutorial Summary

In this Keras Tutorial, we have learnt what Keras is, its features, installation of Keras, its dependencies and how easy it is to use Keras to build a model with the help of a basic binary classifier example.

The complete workflow is to install Keras with a supported backend, validate and split the data, define the model, compile it with a suitable loss and optimizer, train while monitoring validation results, and evaluate once on held-out test data. The trained model can then generate predictions or be saved in the native Keras format for later use.