Keras is the friendliest way to build deep learning models in Python. In a few readable lines, you can create a neural network, train it on data and use it to make predictions. In this module you'll learn what Keras is, how it fits with TensorFlow, how to get set up for free, and you'll build your first working model.
- Level: Beginner
- Time: about 30 minutes
- Needs: Basic Python (variables, lists, functions)
By the end of this module you will be able to
- Explain what Keras is and what it's used for
- Describe how Keras relates to TensorFlow, JAX and PyTorch
- Explain what a neural network is, in simple terms
- Set up Keras for free in Google Colab or on your own computer
- Describe the five steps of every Keras project
- Build, train, evaluate and use your first Keras model
- Recognise the most common beginner errors
1.1What is Keras?
Keras is a free, open-source Python library for building and training neural networks, the technology behind modern AI such as image recognition, speech-to-text, translation and chatbots. It was created by François Chollet, an engineer at Google, and first released in 2015.
Keras is designed for humans. Instead of writing hundreds of lines of complicated maths, you describe your model as a stack of simple building blocks called layers, and Keras does the hard work for you.
Like building with LEGO
Keras gives you ready-made blocks (layers) that click together. You choose which blocks to use and in what order. You don't need to know how each block was manufactured to build something impressive, but the better you understand the blocks, the better your builds become.
A neural network in one minute
A neural network is made of layers of simple units called neurons. Each neuron takes some numbers in, multiplies them by weights, adds them up, and passes the result on. At first the weights are random, so the network's answers are nonsense. During training, the network is shown thousands of examples with the right answers, and it gradually adjusts its weights to make fewer mistakes. That's all "learning" means here.
You don't need to understand the maths to use Keras. If you'd like the full story, our free Neural Networks course explains every step. This Keras track focuses on the practical skill: building models that work.
1.2Keras, TensorFlow, JAX and PyTorch
People often mention Keras and TensorFlow together. Here's how they relate:
| Name | What it is |
|---|---|
| Keras | The easy, high-level interface you use to build and train models |
| TensorFlow | Google's deep learning engine, and the most common Keras backend. When you install TensorFlow, you get Keras too |
| JAX | A fast numerical engine from Google, popular in research |
| PyTorch | Meta's deep learning library, very popular in research and industry |
Since Keras 3 (released in late 2023), the same Keras code can run on TensorFlow, JAX or PyTorch. In this track we use the default, TensorFlow, and you never need to change it. It's still useful to know: the Keras skills you learn here work with all three.
1.3Getting set up
You have two options. For this track, we recommend Google Colab: it's free, runs in your browser, and has Keras ready to go.
| Option | How | Best for |
|---|---|---|
| Google Colab (recommended) | Go to colab.research.google.com, sign in with a Google account and create a new notebook. Paste code into a cell and press the play button (or Shift + Enter) | Beginners; nothing to install; free GPUs for bigger models |
| Your own computer | Install Python, then run pip install tensorflow scikit-learn in a terminal, and use Jupyter Notebook or VS Code | Working offline and on your own projects |
Check everything works by running this in a new cell:
import keras
print(keras.__version__) # e.g. 3.x
print(keras.backend.backend()) # usually "tensorflow"
Want to train faster?
In Colab, go to Runtime → Change runtime type and choose a GPU. You won't need it for this module, but it makes a big difference for image models later in the track.
1.4The five steps of every Keras project
Almost every Keras project, from a tiny example to a model that recognises thousands of objects, follows the same five steps:
| Step | Question it answers | You'll learn more in |
|---|---|---|
| 1. Define | What layers does my model have? | Modules 3 and 6 |
| 2. Compile | How should it measure mistakes and improve? | Module 4 |
| 3. Fit | How long should it train, and on what? | Module 5 |
| 4. Evaluate | How good is it on data it has never seen? | Module 5 |
| 5. Predict | What does it say about new examples? | Module 5 |
If you've used scikit-learn, this will feel familiar: it's the same fit-and-predict idea, with an extra compile step where you choose how the network learns.
1.5Watch a network learn
Before we write any Python, let's see a neural network train. Below are 200 points in two interlocking "moon" shapes. A straight line can't separate them, but a neural network can learn a curved boundary. This network is really training, right here in your browser, using the same method Keras uses (the Adam optimiser).
Try it: train a neural network
Epoch 0Notice three things. The loss (how wrong the network is) falls as it trains. The boundary starts as a random mess and bends into shape. And the Keras code on the right, just five lines, describes exactly this network.
1.6Your first Keras model
Now let's build the same kind of model in real Keras. We'll create 1,000 moon-shaped points, split them into training and test sets, and follow the five steps.
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import numpy as np
import keras
from keras import layers
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
print("Keras version:", keras.__version__)
print("Backend:", keras.backend.backend())
keras.utils.set_random_seed(42)
# 1. Data: 1,000 points in two interlocking "moon" shapes
X, y = make_moons(n_samples=1000, noise=0.2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
# 2. DEFINE the model
model = keras.Sequential([
keras.Input(shape=(2,)), # each point has 2 numbers
layers.Dense(16, activation="relu"), # hidden layer 1: 16 neurons
layers.Dense(16, activation="relu"), # hidden layer 2: 16 neurons
layers.Dense(1, activation="sigmoid"), # output: probability of class 1
])
# 3. COMPILE: how should it learn?
model.compile(optimizer="adam", loss="binary_crossentropy",
metrics=["accuracy"])
# 4. FIT: train for 100 passes through the data
history = model.fit(X_train, y_train, epochs=100, batch_size=32, verbose=0)
print(f"Loss: {history.history['loss'][0]:.3f} (epoch 1) -> "
f"{history.history['loss'][-1]:.3f} (epoch 100)")
# 5. EVALUATE on data the model has never seen
loss, acc = model.evaluate(X_test, y_test, verbose=0)
print(f"Test accuracy: {acc:.3f}")
# 6. PREDICT for two brand-new points
new_points = np.array([[-0.5, 0.8], [1.5, -0.4]])
probs = model.predict(new_points, verbose=0)
for point, p in zip(new_points, probs.ravel()):
print(f"Point {point.tolist()}: {p:.1%} chance of class 1")
Keras version: 3.15.1 Backend: tensorflow Loss: 0.771 (epoch 1) -> 0.087 (epoch 100) Test accuracy: 0.980 Point [-0.5, 0.8]: 0.3% chance of class 1 Point [1.5, -0.4]: 99.5% chance of class 1
Your numbers may be very slightly different, depending on your Keras version and computer.
What the code does
| Line | What it means |
|---|---|
keras.Input(shape=(2,)) | Each example has 2 numbers (its x and y position) |
layers.Dense(16, activation="relu") | A layer of 16 neurons, each connected to every input. "relu" lets the network learn curves (Module 3) |
layers.Dense(1, activation="sigmoid") | One output neuron giving a probability between 0 and 1 |
optimizer="adam" | The method used to adjust the weights; Adam is a great default |
loss="binary_crossentropy" | How mistakes are measured for yes/no problems (Module 4) |
epochs=100 | Go through the whole training set 100 times |
batch_size=32 | Update the weights after every 32 examples |
What the output tells us
- The loss fell from 0.771 to 0.087: the model made far fewer mistakes by the end of training.
- Test accuracy is 98% on 200 points the model never saw during training.
- Predictions are probabilities. The first new point has a 0.3% chance of being class 1 (so it's almost certainly class 0), while the second is 99.5% likely to be class 1.
- This model has 337 weights to learn. Big image and language models have millions or billions, but they're built with the very same five steps.
1.7Common beginner errors
Everyone hits these at first. Knowing them now will save you hours.
| Error or symptom | Usual cause | Fix |
|---|---|---|
ValueError mentioning shape or "incompatible" | Your data doesn't match keras.Input(shape=...) | Check X.shape and set the input shape to match (Module 2) |
| "You must call compile() before…" | You tried to fit() before compile() | Always compile first |
| Accuracy stuck at about 50%, or loss not falling | Data not scaled, learning rate too high, or the wrong loss | Scale your inputs (Module 2) and check the loss matches the task (Module 4) |
Loss becomes nan | The numbers have blown up | Scale your data and lower the learning rate |
| Great training accuracy, poor test accuracy | Overfitting: the model memorised the training data | More data, a smaller model, or regularisation (Module 7) |
ModuleNotFoundError: No module named 'keras' | TensorFlow or Keras isn't installed | Run pip install tensorflow, or use Colab |
SummaryKey takeaways
- Keras is a free Python library for building neural networks with simple, readable code.
- A neural network learns by adjusting its weights to make fewer mistakes on examples.
- Keras is the interface; a backend (usually TensorFlow, or JAX or PyTorch) does the maths.
- The easiest setup is Google Colab: free, in your browser, with Keras installed.
- Every project follows five steps: define → compile → fit → evaluate → predict.
- Your first model reached 98% test accuracy with just a few lines of code.
- Most beginner errors come from shapes, unscaled data or the wrong loss.
Check your understanding
Your Keras roadmap
- 01Introduction to KerasYou are here
- 02Tensors and Data for KerasShapes, scaling and splitting data
- 03The Sequential API and Dense LayersStacking layers into a model
- 04Compiling ModelsLosses, optimisers and metrics
- 05Training and Evaluatingfit(), validation and callbacks
- 06The Functional APIMultiple inputs, outputs and branches
- 07RegularisationDropout, batch normalisation and early stopping
- 08Image Classification with KerasCNNs and data augmentation
- 09Text and Sequences with KerasEmbeddings, LSTMs and text classification
- 10Pretrained Models, Saving and DeploymentFine-tuning and sharing your models
Next module
Tensors and Data for Keras