Deep Learning with Keras
Study Notes: Neural Networks with Keras and TensorFlow
1. Keras, TensorFlow, and the Learning Workflow
Keras is a high-level API for building and training neural networks. It is designed to support fast experimentation: a model can be described and tested with relatively few steps. Keras is integrated into TensorFlow, so installing TensorFlow also provides access to its Keras API.
Keras represents the model at a high level, while TensorFlow supplies lower-level functionality. Earlier versions of Keras could run on different backend libraries; modern TensorFlow Keras is integrated with TensorFlow rather than being a separate API that can be switched among backends.
A productive way to learn neural-network tools is to understand the underlying concepts and then learn how different APIs express them. Once concepts such as layers, losses, optimizers, and training are familiar, differences in syntax between APIs are easier to learn. Knowing multiple APIs can also help practitioners compare their strengths and choose tools appropriate to a problem.
Basic requirements and installation
The coding examples require basic programming ability and some familiarity with Python. A user can install TensorFlow, including Keras, from the command line with:
pip install tensorflow
The machine must satisfy the system requirements for the TensorFlow version being installed.
CPU and GPU computation
A GPU is optional. Neural-network code can run on a CPU, although training may take longer. A compatible GPU can accelerate many deep-learning workloads, but it requires the appropriate TensorFlow and hardware setup.
A practical workflow is to begin on a CPU if GPU support is not already configured. Once the code works, the same computations can be run on a GPU and their speed compared. GPU memory growth may also be enabled in TensorFlow so that memory is allocated as needed instead of reserving all available GPU memory immediately.
2. Samples, Labels, and Data Preparation
A supervised-learning task requires examples and their corresponding answers.
A sample, also called an input, is one data point provided to the model. Examples include a headline or an image.
A label, also called a target, is the answer associated with a sample. For a headline, the label might be positive or negative sentiment; for an image, it might be cat or dog.
Before processing data, the intended task and model interface must be understood. The data must be in a format accepted by the model, and it may also need to be transformed into a form that helps the model learn efficiently.
Inputs and targets in Keras
During training, a Keras model receives inputs and targets through its fit operation. The input data, conventionally called x, may be supplied in formats such as NumPy arrays, TensorFlow tensors, dictionaries, TensorFlow datasets, or Keras generators. The targets, conventionally called y, must use a compatible format.
When both inputs and targets are NumPy arrays, they should correspond in order: the label at a given position must belong to the sample at that same position. This alignment must be preserved whenever data is shuffled or otherwise rearranged.
A synthetic clinical-trial dataset
A simple example uses patient ages as samples and whether patients experienced side effects as labels. The imagined trial includes individuals from ages 13 to 100, with a strong relationship between age group and outcome:
For people younger than 65, approximately 95% are labeled as having no side effects.
For people aged 65 or older, approximately 95% are labeled as having side effects.
In this example, ages are the input samples. A label of 0 represents no side effects, and a label of 1 represents side effects. The data can be generated programmatically by drawing random ages from the two age ranges and appending the associated labels.
This is intentionally simple synthetic data. It demonstrates the mechanics of preparing and training a model, rather than representing a complete or realistic clinical analysis.
Converting, shuffling, and scaling numerical data
The generated lists are converted into NumPy arrays before being passed to the model. The samples and labels can then be shuffled together so that their original ordering does not create an unintended pattern. They must be shuffled in the same way to preserve sample–label correspondence.
Normalization and standardization are data transformations that can put features on more useful scales for learning. In the age example, min–max scaling maps ages from their original range, 13 to 100, to a range from 0 to 1:
For this dataset, xmin=13 and xmax=100. Scaling does not change the ordering of ages; it changes their numerical range.
Some transformation functions expect data with a particular number of dimensions. A one-dimensional list of values may need to be reshaped before it can be passed to a scaling function. Reshaping changes the array’s structure, not the underlying values.
3. Sequential Models and Neural-Network Structure
A sequential model is a linear stack of layers: the output of one layer is passed to the next. It is a straightforward model type when each layer has one input and one output path.
A simple numerical-data model can have:
An input shape specified for the first hidden layer.
One or more fully connected hidden layers.
An output layer whose units correspond to the possible classes.
Input and hidden layers
The input data determines the model’s input layer. In a sequential model, the input shape is specified in the first layer so that the model knows what data dimensions to expect. The first explicitly added dense layer is therefore a hidden layer, not the input layer itself.
A dense layer, also called a fully connected layer, connects each unit to the outputs of the preceding layer. Its units are also called neurons or nodes. The number of units in a hidden layer is a design choice; it is commonly selected and adjusted through experimentation.
A hidden layer is often followed by an activation function, which introduces nonlinearity into the model. The rectified linear unit, or ReLU, is a commonly used hidden-layer activation.
Output layers and class probabilities
For a classification task with two possible classes, an output layer can contain two units, one for each class. A softmax activation converts the output scores into a probability distribution: the class probabilities are nonnegative and sum to 1.
For example, one output might represent “no side effects” and the other “side effects.” The predicted class is usually the class with the larger output probability.
A model summary displays the layer sequence, output shapes, and parameter counts. Trainable parameters are weights and biases that can be updated during training. The number of units and layers affects the model’s architecture and its parameter count.
4. Compiling and Training a Model
Before training, a model is compiled with choices that specify how it will learn and how its performance will be measured.
Optimizer, loss, and metrics
An optimizer updates the model’s parameters to reduce error. Adam is a commonly used optimizer.
The learning rate controls the size of parameter updates. A learning rate that is too large can make learning unstable, while one that is too small can make training slow.
A loss function quantifies the difference between model predictions and target labels. Training aims to reduce this value.
A metric summarizes performance in a form that is easy to interpret. Accuracy is a common classification metric.
For a classification model with two output units and integer class labels, sparse categorical cross-entropy is one suitable loss. If the targets are instead represented as one-hot vectors, categorical cross-entropy is appropriate.
Batches and epochs
Training repeatedly processes examples from the training set.
A batch is a group of samples processed together before the model updates its parameters. The batch size controls the number of samples in each group.
An epoch is one complete pass through the training data.
For example, training for 30 epochs means that the model processes the training set 30 times. Shuffling the training data between epochs helps prevent the model from depending on an accidental ordering of examples.
Training output commonly includes loss and accuracy for each epoch. In the synthetic age example, performance improves as training proceeds: loss decreases and accuracy increases. A high accuracy on simple data illustrates that a basic Keras model can be trained with a small amount of code, but results on simple synthetic data do not establish that a model will perform well on more complex real-world tasks.
5. Training, Validation, and Overfitting
A model is usually expected to work on data it did not encounter during training. A validation set helps assess this ability while model development is in progress.
What validation measures
The model trains on the training set. At the end of each epoch, it can also make predictions on the validation set and report validation loss and accuracy. The validation data is used to assess generalization; it is not used to update the model’s weights during the training process.
A validation set can be supplied as a separate dataset, or Keras can reserve a fraction of the training data using a validation-split option. When a fraction is reserved, those examples are held out from training.
Why shuffling matters with a validation split
When a validation fraction is taken from a dataset, the split may occur before the remaining training data is shuffled for training. If the original dataset is ordered by class or another relevant feature, the held-out portion might not represent the full dataset. For example, the validation set could contain mostly one class.
To reduce this risk, shuffle the data before passing it to the model, while keeping samples and labels aligned. Separately supplied validation data should also be prepared consistently with the training data.
Overfitting and generalization
Overfitting occurs when a model learns the training examples very well but performs less well on new examples. It is indicated by a substantial gap between training and validation performance: for instance, high training accuracy alongside lower validation accuracy.
When training and validation metrics are similar, the model appears to generalize more consistently to the held-out data. If validation performance lags behind training performance, possible responses include gathering or augmenting data, adjusting the model, or changing training choices.
Validation data supports model development, but it is not the final independent assessment. A separate test set is useful for that purpose.
6. Inference, Test Sets, and Confusion Matrices
Inference is the use of a trained model to make predictions on data. The model applies what it learned during training to samples it has not seen before.
For example, a model trained on cat and dog images could be used to classify new images submitted by users. The hope is that learned features will generalize to these new images.
Using a test set
A test set is held apart from training and validation. After the model has been developed, it can be used to estimate how well the model performs on unseen data. The model receives the test samples for prediction, but their labels are not needed to produce predictions.
Test data must be processed in the same way as training data. For numerical data, that includes applying the same scaling parameters. For images, it includes applying the same resizing and model-specific preprocessing.
If true test labels are available, they can be compared with predictions to evaluate performance. In many deployment situations, labels for new incoming data are not immediately available, so the model can still infer predictions without an immediate accuracy calculation.
Probability outputs and predicted classes
A model with a softmax output returns a probability for each class for every sample. The predicted class is the class with the highest probability. Taking the index of the largest probability converts the probability vector into a single predicted class label.
For example, if the first output has the largest probability, the model predicts the class associated with output index 0. The mapping between indices and class names must be known to interpret results correctly.
Confusion matrices
A confusion matrix compares predicted classes with true classes. It shows how many examples of each true class were assigned to each predicted class. The exact axis orientation depends on the plotting convention, so the axis labels should always be checked.
Correct predictions lie along the matrix’s main diagonal when the true and predicted class orderings match. Off-diagonal entries represent errors, showing which classes were confused.
In the clinical-trial example, the model made 396 correct predictions out of 420 total test predictions, corresponding to about 94% accuracy. A confusion matrix provides more information than a single accuracy value because it reveals class-specific error patterns.
Accuracy can be calculated as:
7. Saving and Loading Models
A trained model can be saved so it can be restored later, used for inference, or continue training. Different saving methods preserve different parts of a model.
Saving the complete model
Saving the complete model is the most comprehensive option. It preserves:
The model architecture, including layers and their configuration.
The weights, which are the learned parameter values.
The training configuration, such as the chosen loss and optimizer.
The optimizer state, which can allow training to resume from its saved state.
After loading, the model can be inspected with a summary and can retain the configuration used when it was compiled.
Saving only the architecture
A model architecture can be serialized as a JSON or YAML description. This records the structure of the model but does not, by itself, preserve learned weights or the complete training state.
A model reconstructed from architecture alone must have its weights loaded separately or be trained again. It also needs to be compiled before further training.
Saving only the weights
Saving only the weights is useful when the architecture will be recreated separately. The new model must have a compatible architecture before those weights can be loaded. In practice, its layers and parameter shapes must match the saved weights.
The three approaches therefore serve different needs:
Complete model: restores architecture, learned weights, and training configuration.
Architecture only: restores the model structure.
Weights only: restores learned parameter values into a compatible model.
8. Preparing Image Data for Convolutional Neural Networks
Images require additional organization and preprocessing before they can be supplied to a model. A convolutional neural network (CNN) processes spatially arranged image data and is commonly used for image classification.
Organizing cat and dog images
A cat-versus-dog dataset can be organized into directories for training, validation, and testing. Within each set, separate class directories hold cat images and dog images.
A dataset does not always need to be used in full. A smaller subset can make development and experimentation faster. The subset should still be split into training, validation, and test data in a deliberate way.
When images are selected from a larger collection, file names or directory locations may indicate their class. The resulting data should be checked to ensure that the intended numbers of images and classes were found.
Directory iterators and image batches
An image data generator can load images from directories and return batches that a model can use. A directory iterator can also associate images with labels based on their class directories.
Image loading commonly includes resizing each image to a consistent height and width. For example, images may be resized to 224×224 pixels if that is the input size required by the chosen model. Color images typically have three channels: red, green, and blue.
The batch size determines how many images are supplied together. When training and validation data are separate directory iterators, both can be passed to the model during fitting. If the iterator already yields labels with its images, the labels do not need to be supplied separately.
Preserving test-label alignment
A test iterator may need to avoid shuffling when predictions will later be compared with a separately obtained list of test labels. If the iterator reorders the samples but the labels remain in their original order, the comparison will be invalid.
The required principle is one-to-one alignment: each predicted output must be compared with the true label for the same image. This alignment is essential for a valid confusion matrix.
9. Building and Evaluating a CNN
A CNN can be constructed as a sequential stack of layers. A simple cat-versus-dog model can use convolution, pooling, flattening, and dense classification layers.
Convolution and pooling
A convolutional layer applies filters to local regions of an image. Each filter can learn patterns such as edges, textures, or more complex visual features. The number of filters determines how many feature maps the layer produces.
The kernel size specifies the spatial size of each filter. A 3×3 kernel is a common choice for image models.
Padding controls how the convolution treats image boundaries. With same padding, zeros are added around the image as needed so that the spatial dimensions are preserved through the convolution operation.
A max-pooling layer reduces the spatial dimensions by retaining the largest value in each local region. For example, a 2×2 pooling window with a stride of 2 typically reduces height and width by half.
A CNN may alternate convolutional and pooling layers, with later convolutional layers using more filters than earlier ones.
Flattening and classification
Before a convolutional feature representation is passed to a dense layer, it is often flattened into a one-dimensional vector. The dense output layer then maps the learned features to class scores.
For two classes, an output layer with two units followed by softmax produces a probability for each class. Categorical cross-entropy is appropriate when the targets use one-hot encoding. Another valid two-class setup uses one output unit, sigmoid activation, and binary cross-entropy.
Training results and overfitting
A model built from scratch may reach very high training accuracy while achieving substantially lower validation accuracy. For example, a model might reach 100% training accuracy but only about 69% validation accuracy. This is evidence of overfitting: the model has fitted the training examples better than it generalizes to held-out examples.
Predictions on the test set can be evaluated with a confusion matrix when true test labels are available. In the example, the scratch-built CNN performed at roughly the same level on the test data as on the validation data, reinforcing that validation performance can help anticipate test performance.
10. Fine-Tuning Pretrained Models: VGG16
A pretrained model is a model that has already learned from a large dataset. Fine-tuning adapts some or all of that model for a new task.
VGG16 and its original task
VGG16 is a deep image-classification model trained on ImageNet, a collection containing many image classes. The model originally predicts among 1,000 classes, including cats and dogs.
Because cats and dogs were represented in its original training data, a VGG16 model can already contain useful features for distinguishing them. Adapting it to a cat-versus-dog task therefore requires less learning than starting from an untrained model.
VGG16 is relatively large: the model discussed contains roughly 138 million parameters and occupies about 553 megabytes on disk. Its size reflects the computational and memory demands of a large model.
Replacing the output layer
To adapt VGG16 for two classes, its original output layer is removed and replaced with a layer containing two output units followed by softmax. The remaining layers provide features learned from the original task.
A common fine-tuning approach is to freeze the earlier layers. A frozen layer’s weights are not updated during training. If the pretrained layers already represent useful visual features, training only the new output layer can adapt the classifier without relearning all the existing features.
In this setup, the original VGG16 structure is retained except for its final output layer, and the new model is trained to classify cat and dog images. Only the new output layer is trainable.
Fine-tuning results
After a small number of training epochs, the fine-tuned model achieved approximately 99% training accuracy and 98% validation accuracy in the example. Its performance was much more balanced than that of the scratch-built CNN, which reached high training accuracy but much lower validation accuracy.
On the test set, the fine-tuned model made 96 correct predictions out of 100, for an accuracy of 96%. These results illustrate the potential benefit of reusing pretrained features, especially when the new task resembles categories in the model’s original training data.
11. MobileNet: Lightweight Image Models
MobileNet refers to a family of lightweight convolutional neural networks designed for efficient use on devices with limited storage, memory, or computation. These models can support image classification, detection, and similar tasks.
The MobileNet model discussed is substantially smaller than VGG16:
VGG16 occupies about 553 megabytes and has roughly 138 million parameters.
A large MobileNet example occupies about 17 megabytes and has roughly 4.2 million parameters.
Fewer parameters generally mean lower storage and memory demands. This can make MobileNet more suitable for mobile devices and other resource-constrained environments.
The trade-off is that a lightweight model may be somewhat less accurate than a larger model. The reduction in accuracy is not always large, and the appropriate balance depends on the task’s requirements.
Preparing images for MobileNet
Images must be resized to the dimensions expected by the model, then converted into an array shape compatible with it. MobileNet’s preprocessing function scales pixel values from their usual range of 0 to 255 into a range from −1 to 1:
The model-specific preprocessing step matters because pretrained weights were learned using a particular input transformation. Feeding images in a different format can reduce performance.
Example predictions
For each image, MobileNet returns probabilities for the ImageNet classes. The five most probable classes can be inspected, along with their probability estimates. In the examples, MobileNet assigned a high probability to a chameleon-like lizard image, a high probability to espresso for a coffee image, and nearly all probability to strawberry for a strawberry image.
These examples illustrate both the use of a pretrained model for inference and the interpretation of its probability-ranked class predictions.
12. Fine-Tuning MobileNet for a New Dataset
A model can be adapted to a task that differs from its original ImageNet classification task. The example uses a sign-language digit dataset with ten classes, from zero through nine.
Organizing the dataset
The images are first placed into class-specific directories, then arranged into training, validation, and test directories. Each set contains a directory for each of the ten classes.
In the example:
The training set contains approximately 1,700 images.
The validation set contains 30 images per class, or 300 total.
The test set contains 5 images per class, or 50 total.
The exact dataset counts can vary slightly because the original classes do not all contain exactly the same number of images. Each image set is organized consistently so the directory iterator can identify labels from class-directory names.
Image processing
The training, validation, and test directories are loaded using image data generators. Images are resized to the model’s expected dimensions, and MobileNet’s preprocessing function scales their pixel values. The data is supplied in batches.
The test set is kept unshuffled when predictions will be compared with the iterator’s class labels. The same alignment principle used for cat and dog images applies to all multiclass classification tasks.
Constructing and freezing the adapted model
The pretrained MobileNet model has an output layer for its original ImageNet classes. To adapt it, that original output portion is removed and replaced with a new output layer containing ten units, one for each digit class. Softmax produces probabilities over those ten classes.
The MobileNet model uses Keras’s functional model structure. In a functional model, layers can be connected by explicitly passing the output of one layer into another, allowing more flexible architectures than a simple linear stack.
The example retains the earlier MobileNet layers and chooses a subset of later layers to remain trainable. The number of trainable layers is a design choice that should be tested experimentally. Freezing more layers preserves more of the pretrained representation; training more layers gives the model more opportunity to adapt but also increases computation and can affect generalization.
Results and evaluation
The fine-tuned model is trained using the training batches and evaluated against the validation batches. In the example, training accuracy reaches 100%, while validation accuracy reaches approximately 92%. This indicates good performance with some remaining gap between training and validation results.
The model is then evaluated on the test set using predictions and a confusion matrix. It makes about 45 correct predictions out of 50, giving a test accuracy of approximately 90%. The confusion matrix reveals which digit classes are predicted correctly and which are confused.
This example demonstrates transfer learning: a model’s representations learned from one dataset are reused for a new dataset. Fine-tuning determines how much of the pretrained model is retained and how much is adapted to the new task.
13. Data Augmentation for Images
Data augmentation creates modified versions of existing training examples. For images, transformations can include rotation, shifts in width or height, zooming, changes to color channels, and horizontal flipping.
Augmentation has two related benefits:
It increases the variety of examples available for training.
It can reduce overfitting by making it harder for the model to memorize only the exact training images.
An image data generator can apply transformations such as:
Rotation: turns an image by a selected amount. In Keras, the rotation range is specified in degrees.
Width and height shifts: move the image horizontally or vertically, often specified as a fraction of image dimensions.
Shear and zoom: alter the image geometry or scale.
Channel shifts: modify color-channel values.
Horizontal flipping: mirrors the image from left to right.
These transformations are applied according to the configured ranges, so generated versions can differ from one another. A dog image, for example, might be shifted, rotated, or flipped, yielding additional training variations.
Augmentation should reflect transformations that are plausible for the task. If a transformation changes the meaning of an image or creates unrealistic examples, it can harm learning rather than help it. When the goal is to expand the dataset itself, generated images can also be saved and incorporated into the training data.
Data augmentation increases the diversity of training examples; it does not provide new independently collected observations, but it can help a model become more robust to expected variations in its inputs.
14. End-to-End Workflow
A typical image-classification workflow combines the concepts above:
Define the task and identify the samples and labels.
Organize the dataset into training, validation, and test sets, maintaining correct class labels.
Preprocess the data into the format expected by the model, including resizing, scaling, and any model-specific transformations.
Build or adapt a model, using either a model created from scratch or a pretrained model.
Compile the model with a suitable optimizer, loss function, and metric.
Train on the training set while monitoring validation performance.
Check for overfitting by comparing training and validation results.
Run inference on the test set after model development.
Evaluate predictions with a confusion matrix when true test labels are available.
Save the model in a form appropriate for later inference or continued training.
The core principle is that data preparation, model input requirements, and evaluation procedures must remain consistent. A strong training result is meaningful only when the model also performs well on appropriately held-out data.

Ask anything
We've read this whole study set, so questions about it get the best answers.