So far you've built networks by hand to understand how they work. Now it's time to use the tools professionals use. Keras lets you build, train and use a neural network in a handful of lines, while it handles the maths, backpropagation and optimisation for you.
- Level: Intermediate
- Time: about 40 minutes
- Needs: Modules 1 to 5, Python basics
By the end of this module you will be able to
- Explain what TensorFlow and Keras are, and how they compare with PyTorch
- Set up Keras on your computer or in Google Colab
- Follow the five-step Keras workflow: define, compile, fit, evaluate, predict
- Build a Sequential model with Dense layers
- Choose the right output layer and loss for any task
- Read a model summary and count parameters
- Train with a validation set and read the training history
- Save a trained model and load it again
6.1What are TensorFlow and Keras?
TensorFlow is a free deep learning library created by Google. It does the heavy lifting: fast maths on CPUs and GPUs, and automatic backpropagation (Module 5). Keras is the friendly layer on top. It lets you describe a network in plain, readable code, like stacking building blocks.
Like driving a car
TensorFlow is the engine: powerful and complicated. Keras is the steering wheel, pedals and dashboard. You can drive perfectly well without ever opening the bonnet, but it helps to know roughly what the engine does, which is exactly what Modules 1 to 5 gave you.
| Keras (with TensorFlow) | PyTorch | |
|---|---|---|
| Made by | Meta (Facebook) | |
| Style | High-level and concise: build, compile, fit | More hands-on: you write the training loop yourself |
| Best for | Learning, fast prototyping, many business projects | Research and custom models |
| Popularity | Very widely used in industry | The most common choice in research |
We use Keras in this track because it's the easiest way to learn. The ideas transfer directly to PyTorch: layers, activations, losses, optimisers and epochs are exactly the same.
6.2Getting set up
| Option | How | Good for |
|---|---|---|
| Google Colab (easiest) | Go to colab.research.google.com, sign in and start a notebook. TensorFlow and Keras are already installed, and you can use a free GPU | Beginners, no installation needed |
| Your own computer | Run pip install tensorflow in a terminal | Working offline and on your own projects |
Then, at the top of your code:
import keras
from keras import layers
print(keras.__version__)
6.3The five-step Keras workflow
Almost every Keras project follows the same five steps. Once you know them, you can build almost anything.
| Step | Code | What it does |
|---|---|---|
| 1. Define | keras.Sequential([...]) | Stack the layers of your network |
| 2. Compile | model.compile(...) | Choose the optimiser, loss function and metrics |
| 3. Fit | model.fit(X, y, ...) | Train: forward pass, loss, backpropagation and updates, for many epochs |
| 4. Evaluate | model.evaluate(X_test, y_test) | Measure performance on unseen data |
| 5. Predict | model.predict(X_new) | Use the trained model on new data |
If you've used scikit-learn in the Machine Learning track, this will feel familiar: it's the same fit-and-predict idea, with an extra "compile" step to choose how the network learns.
6.4Step 1: define the model
A Sequential model is a simple stack of layers, where data flows straight through from top to bottom. The most common layer is Dense: a fully connected layer, where every neuron connects to every neuron in the layer before (Module 1).
model = keras.Sequential([
keras.Input(shape=(30,)), # input: 30 features
layers.Dense(16, activation="relu"), # 16 neurons, ReLU
layers.Dense(8, activation="relu"), # 8 neurons, ReLU
layers.Dense(1, activation="sigmoid"), # 1 output, sigmoid
])
Counting the parameters
Each Dense layer has (inputs × neurons) weights plus one bias per neuron:
| Layer | Calculation | Parameters |
|---|---|---|
| Dense(16) | 30 × 16 + 16 | 496 |
| Dense(8) | 16 × 8 + 8 | 136 |
| Dense(1) | 8 × 1 + 1 | 9 |
| Total | 641 |
You can check this any time with model.summary(), as you'll see in the Python example.
6.5Step 2: compile, and choosing the right setup
Compiling tells Keras how to learn. You choose three things:
| Setting | What it is | Usual choice |
|---|---|---|
optimizer | How weights are updated (Module 4) | "adam" |
loss | What the network minimises (Module 4) | Depends on the task |
metrics | Extra scores to report while training | ["accuracy"] for classification, ["mae"] for regression |
The output layer and the loss must match your task. Getting this wrong is one of the most common beginner mistakes. Use the builder below to generate the right code for any task.
Try it: Keras model builder
6.6Step 3: fit, and reading the training history
history = model.fit(X_train, y_train,
epochs=50, # passes through the data
batch_size=32, # examples per weight update
validation_split=0.2) # keep 20% aside to check
| Setting | Meaning |
|---|---|
epochs | How many full passes through the training data (Module 4) |
batch_size | How many examples per weight update; 32 is a common default |
validation_split | Holds back a share of the training data. The network never trains on it; Keras just scores it after every epoch, to spot overfitting early |
fit() returns a history: the loss and metrics after every epoch. Always plot it.
6.7A complete Keras project
Here are all five steps together, plus saving the model, on the breast cancer dataset you know from the Machine Learning track. Notice that we still scale the features first: neural networks, like KNN and SVMs, train much better on scaled data.
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import keras
from keras import layers
keras.utils.set_random_seed(42)
# 1. Prepare the data (just like the Machine Learning track)
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
scaler = StandardScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)
# 2. DEFINE the network
model = keras.Sequential([
keras.Input(shape=(30,)), # 30 features per tumour
layers.Dense(16, activation="relu"), # hidden layer 1
layers.Dense(8, activation="relu"), # hidden layer 2
layers.Dense(1, activation="sigmoid"), # output: probability
])
# 3. COMPILE: choose the optimiser, loss and metrics
model.compile(optimizer="adam", loss="binary_crossentropy",
metrics=["accuracy"])
model.summary(line_length=60)
# 4. FIT: train, keeping 20% of the training data aside for validation
history = model.fit(X_train, y_train, epochs=50, batch_size=32,
validation_split=0.2, verbose=0)
for e in [0, 9, 49]:
h = history.history
print(f"Epoch {e+1:2}: loss={h['loss'][e]:.3f} "
f"val_loss={h['val_loss'][e]:.3f} val_accuracy={h['val_accuracy'][e]:.3f}")
# 5. EVALUATE on the test set
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)
print(f"Test accuracy: {test_acc:.3f}")
# 6. PREDICT probabilities for new tumours
probs = model.predict(X_test[:3], verbose=0).ravel()
print("Probabilities (benign):", [f"{p:.4f}" for p in probs], "| true labels:", y_test[:3])
# 7. SAVE and reload
model.save("cancer_model.keras")
reloaded = keras.models.load_model("cancer_model.keras")
print("Reloaded model accuracy:", round(reloaded.evaluate(X_test, y_test, verbose=0)[1], 3))
Model: "sequential" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩ │ dense (Dense) │ (None, 16) │ 496 │ ├──────────────────────────┼───────────────────┼───────────┤ │ dense_1 (Dense) │ (None, 8) │ 136 │ ├──────────────────────────┼───────────────────┼───────────┤ │ dense_2 (Dense) │ (None, 1) │ 9 │ └──────────────────────────┴───────────────────┴───────────┘ Total params: 641 (2.50 KB) Trainable params: 641 (2.50 KB) Non-trainable params: 0 (0.00 B) Epoch 1: loss=0.626 val_loss=0.566 val_accuracy=0.824 Epoch 10: loss=0.167 val_loss=0.168 val_accuracy=0.934 Epoch 50: loss=0.038 val_loss=0.040 val_accuracy=0.989 Test accuracy: 0.956 Probabilities (benign): ['0.0000', '0.9999', '0.0003'] | true labels: [0 1 0] Reloaded model accuracy: 0.956
What the output tells us
- The summary confirms our hand calculation: 496 + 136 + 9 = 641 trainable parameters.
- The history shows loss falling from 0.63 to 0.04, while validation accuracy rises from 82% to 99%. Training and validation loss stay close, so there's no sign of overfitting.
- Test accuracy is 95.6% on tumours the network has never seen.
predict()returns probabilities from the sigmoid output. Here the network is very confident, and all three are correct.- Saving with
model.save()stores the architecture, weights and settings in one.kerasfile. The reloaded model scores exactly the same.
Is a neural network the best choice here?
In the Machine Learning track, logistic regression scored about 97% on this same dataset. For small, table-shaped data like this, simpler models are often as good or better (Module 1). We use it here because it's a clear, fast example. Neural networks really shine on images, text and sound.
6.8Beyond Sequential
Sequential models are a straight stack. For networks with multiple inputs, multiple outputs or branches, Keras has the Functional API, where you connect layers like building a pipeline:
inputs = keras.Input(shape=(30,))
x = layers.Dense(16, activation="relu")(inputs)
x = layers.Dense(8, activation="relu")(x)
outputs = layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs) # same network as before
You'll use it for more advanced designs later in the track, like transfer learning (Module 11).
| Common layer | Used for | Module |
|---|---|---|
Dense | Fully connected layers | This one |
Dropout, BatchNormalization | Training better, reducing overfitting | 7 |
Conv2D, MaxPooling2D | Images | 8 |
LSTM, GRU | Sequences | 9 |
MultiHeadAttention | Transformers | 10 |
SummaryKey takeaways
- TensorFlow is the engine; Keras is the easy-to-use interface on top.
- The five steps: define → compile → fit → evaluate → predict.
- A Sequential model stacks layers; Dense layers are fully connected.
- Parameters per Dense layer = inputs × neurons + neurons.
- Match the output layer and loss to the task: linear + MSE, sigmoid + binary cross-entropy, softmax + categorical cross-entropy.
- Use validation_split and plot the history to spot problems early.
- Save with
model.save("name.keras")and load withkeras.models.load_model().
Check your understanding
Your neural networks roadmap
- 01Introduction to Neural NetworksWhat neural networks are and how they work
- 02The Perceptron and the Artificial NeuronBuild a single neuron from scratch
- 03Activation FunctionsSigmoid, tanh, ReLU and softmax
- 04Loss Functions and Gradient DescentHow networks measure and reduce error
- 05BackpropagationHow every weight learns its share of the blame
- 06Building Networks with KerasYou are here
- 07Training Better NetworksOverfitting, dropout, batch normalisation, early stopping
- 08Convolutional Neural NetworksTeaching computers to see
- 09Recurrent Neural Networks and LSTMsWorking with sequences
- 10Transformers and AttentionThe architecture behind ChatGPT and Claude
- 11Transfer Learning and Pretrained ModelsStanding on the shoulders of giants
- 12Capstone ProjectBuild and present a deep learning project
Next module
Training Better Networks