Building Keras Models
Deep Learning Study Notes: Training Neural Networks and Image Classification
Recap of Neural Network Training Flow
Training a neural network follows the same fundamental pattern as training any machine learning model:
The model has a set of parameters (weights and biases) that must be learned from data.
A loss function measures the discrepancy between the model’s predictions and the ground truth.
The goal is to find the parameter values that minimize this loss.
Training loop (iterative process):
Input data passes through the network layers to produce predictions.
The predictions and true values are fed into the loss function to compute a loss score.
The loss is sent to an optimizer, which calculates the gradient of the loss with respect to all parameters.
The optimizer updates the weights using the gradient, and the process repeats.
Loss function: A mathematical measure of how far the model’s predictions are from the true answers. Minimizing this loss is the objective of training.
Gradient Descent vs Stochastic Gradient Descent
Gradient Descent (GD): In each iteration, every data point in the entire training set is used to compute predictions, loss, and gradient. One update per epoch.
Stochastic Gradient Descent (SGD): Instead of using all points, a small random subset (a minibatch or simply batch) is used at each step. The gradient is approximated from that batch and the weights are updated immediately.
Epochs and Batches in SGD
Epoch: One full pass through the entire training dataset.
Batch: A small, randomly chosen subset of data processed in one step of SGD.
Pictorially, during SGD:
Training data is divided into batches (e.g., batch 1, batch 2, …, final batch).
For each batch:
Run the batch through the network to get predictions.
Compute the loss and gradient.
Update the weights.
After processing all batches, one epoch is complete.
Number of batches per epoch = ⌈batch sizetotal training samples⌉
Example: 194 training samples, batch size 32 → ⌈194/32⌉=7 batches (first 6 batches of 32, last batch of 2).
Key advantage of SGD: Because weights are updated after each small batch, the model begins to improve quickly without waiting for a full pass through all data. This also reduces computational cost and can help escape shallow local minima.
Batch size: A hyperparameter (commonly 32, 64, 128) that determines how many samples are used per gradient update. Small batch sizes introduce noise but can generalize better; large batch sizes provide more accurate gradients but require more memory.
Overfitting and Regularization
As model complexity increases (more layers, more parameters), the training error typically decreases. However, at some point the validation error (error on unseen data) may start to increase — this is overfitting.
Underfitting: Model is too simple to capture patterns; both training and validation errors are high.
Overfitting: Model memorizes idiosyncrasies of training data; training error is low but validation error rises.
Sweet spot: The optimal complexity where validation error is minimized.
Regularization: Techniques used to prevent overfitting and find models that generalize well.
Two Common Regularization Methods
Early Stopping
Split training data into training set and validation set.
Monitor validation loss (or accuracy) during training.
When validation loss stops improving (flattens or starts to rise), stop training — even if training loss continues to decrease.
Geoff Hinton called early stopping a “beautiful free lunch” because it requires no extra computation and often improves generalization.
Dropout (to be covered later)
A clever regularization technique where randomly selected neurons are “dropped” (ignored) during training, forcing the network to learn redundant representations.
Training Checklist Summary
Get the data ready (preprocessing, splitting).
Design the network (number of hidden layers, neurons, activation functions).
Choose the output layer type (sigmoid for binary, softmax for multi-class, linear for regression).
Choose the loss function (binary cross-entropy, categorical cross-entropy, MSE, etc.).
Choose an optimizer (Adam is a strong default — a flavor of SGD).
Apply regularization (early stopping, dropout).
Train the model using Keras/TensorFlow.
Tensors, TensorFlow, and Keras
What is a Tensor?
A tensor is a generalization of numbers, vectors, and matrices to higher dimensions. Every tensor has a rank (number of dimensions):
Rank 0: Scalar (a single number).
Rank 1: Vector (a list of numbers).
Rank 2: Matrix (a table of numbers).
Rank 3: A cube (a list of matrices). Example: a grayscale image is a rank-2 tensor (height × width); a batch of grayscale images is a rank-3 tensor (batch × height × width).
Rank 4: A list of rank-3 tensors. Example: a color image has three channels (RGB) → rank-3; a batch of color images → rank-4 (batch × height × width × channels).
Rank 5: A list of videos (each video is rank-4).
Higher-rank tensors are built by stacking lower-rank tensors along a new dimension.
Key property: Any tensor can be indexed by iterating through the first dimension, which yields a tensor of one lower rank.
TensorFlow
TensorFlow is a library for deep learning that provides:
Automatic gradient computation (autodiff) — no manual chain rule needed.
Optimizers (SGD, Adam, etc.) ready to use.
Parallel and distributed computing — automatically parallelizes across multiple servers or GPUs.
GPU/TPU support — optimizes computations for graphics processing units or Tensor Processing Units.
Keras
Keras is a high-level API that sits on top of TensorFlow, offering convenience features:
Layer abstraction (e.g.,
Dense,Dropout,Flatten).Activation functions (ReLU, sigmoid, softmax).
Easy data preprocessing, training, and metric reporting.
Pre-trained models for transfer learning.
Keras provides three APIs: Sequential, Functional, and Subclassing. The Functional API (used in this course) is flexible and modular, ideal for building complex architectures.
Heart Disease Prediction with Keras (Binary Classification)
Problem Setup
Dataset: 303 patients, 14 variables (age, gender, cholesterol, etc.). Target: heart disease (0 or 1).
Baseline accuracy (predict majority class, 0): 72.6%.
Preprocessing Steps
Load data into a Pandas DataFrame.
Separate categorical and numeric features.
One-hot encode categorical variables (neural networks cannot handle categorical inputs directly).
Example:
thal→thal_fixed,thal_normal,thal_reversible.
Split into training and test sets (e.g., 80/20) before normalization, to keep test data completely unseen.
Training: 242 rows; Test: 61 rows.
Standardize numeric variables: Subtract mean, divide by standard deviation (so inputs are centered around 0 with unit variance).
This helps neural networks converge faster.
Convert DataFrames to NumPy arrays (Keras expects numeric arrays).
Separate features (X) and target (y). The target column (column index 6) becomes
train_yandtest_y.
Building the Model
The architecture from the previous lecture:
Input layer: 29 features (after one-hot encoding).
Hidden layer: 16 neurons, ReLU activation.
Output layer: 1 neuron, sigmoid activation (binary classification).
inputs = keras.Input(shape=(29,))
x = layers.Dense(16, activation='relu', name='hidden')(inputs)
outputs = layers.Dense(1, activation='sigmoid', name='output')(x)
model = keras.Model(inputs=inputs, outputs=outputs)Parameter count verification:
Hidden layer: 29×16+16=464+16=480 parameters.
Output layer: 16×1+1=17 parameters.
Total: 497 parameters.
Use model.summary() to confirm.
Compilation
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)Compilation step: Keras reorganizes the model for efficient parallel execution (no actual training yet).
Training
history = model.fit(
train_X, train_y,
epochs=300,
batch_size=32,
verbose=1,
validation_split=0.2 # 20% of training data set aside for validation
)Epochs: 300 chosen to observe overfitting patterns.
Batch size: 32 (good default).
Validation split: Keras automatically reserves 20% of training data for validation (not used for gradient updates).
Output interpretation per epoch:
7/7— means 7 batches were processed (194 training samples / 32 ≈ 7).lossandaccuracy— on the training batch (or average over batches).val_lossandval_accuracy— on the held-out validation set after the epoch.
Visualizing Training History
Plot training loss vs. validation loss over epochs. If validation loss flattens or begins to rise while training loss continues to drop, overfitting is occurring.
Plot training accuracy vs. validation accuracy. Accuracy is a discrete, jumpy metric; it can sometimes improve even when loss rises slightly.
Early Stopping in Practice
Instead of manually stopping, Keras callbacks can be used:
from keras.callbacks import EarlyStopping
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
model.fit(..., callbacks=[early_stop])This automatically halts training when validation loss stops improving and restores the best weights.
Evaluation on Test Set
After training, evaluate the final model on the completely unseen test set:
test_loss, test_accuracy = model.evaluate(test_X, test_y)Achieved accuracy: ~83.6% (beating baseline of 72.6%).
This is the realistic estimate of real-world performance.
Computer Vision Fundamentals
Digital Representation of Images
Grayscale image: Each pixel is a single number representing light intensity from 0 (black) to 255 (white).
Represented as a rank-2 tensor (height × width).
Color image (RGB): Each pixel has three values (red, green, blue), each 0–255.
Represented as a rank-3 tensor (height × width × 3) — three “channels”.
Channel: In deep learning, each color (R, G, B) is a channel. A grayscale image has 1 channel; a color image has 3.
Common Computer Vision Tasks (from simplest to most complex)
Image Classification: Assign a single label to the entire image (e.g., “cat” or “dog”).
Localization: Classify the image and also output a bounding box around the object (coordinates of top-left and bottom-right corners).
Object Detection: Detect and localize multiple objects in the same image.
Semantic Segmentation: Classify every pixel in the image (each pixel gets a category label).
Instance Segmentation: Like semantic segmentation, but also distinguishes between different instances of the same category (e.g., separate sheep).
Fashion-MNIST Classification (Multi-class)
Dataset
70,000 grayscale images (28 × 28 pixels) of clothing items across 10 categories.
Categories: T-shirt/top, trouser, pullover, dress, coat, sandal, shirt, sneaker, bag, ankle boot.
Balanced: ~10% per class. Baseline accuracy (random guess) is 10%.
Pre-split into 60,000 training and 10,000 test images (available in Keras as
fashion_mnist).
Model Architecture for Fashion-MNIST
Step 1: Flatten the 28 × 28 image into a vector of length 784.
inputs = keras.Input(shape=(28, 28))
x = layers.Flatten()(inputs) # (28,28) → (784)Step 2: Hidden layer with ReLU activation. 256 neurons works well.
x = layers.Dense(256, activation='relu')(x)Step 3: Output layer — 10 neurons, each representing a class. Use softmax activation to produce probabilities that sum to 1.
Softmax function: Given a vector of raw scores z1,z2,…,zn, the softmax outputs:
softmax(zi)=∑j=1nezjeziThis converts any real numbers into positive probabilities that sum to 1.
outputs = layers.Dense(10, activation='softmax')(x)
model = keras.Model(inputs=inputs, outputs=outputs)Choosing the Loss Function
The choice depends on how the labels are encoded:
Output Label Encoding | Keras Loss Function |
|---|---|
Single binary value (0 or 1) |
|
Integer class index (0 to 9) — sparse |
|
One-hot vector (e.g., [0,0,1,0,…]) |
|
Fashion-MNIST labels come as integers (sparse encoding), so we use sparse_categorical_crossentropy.
Compilation and Training
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(
train_images, train_labels,
epochs=10, # will tune later
batch_size=32,
validation_split=0.2
)Data Visualization
After loading the data, it’s helpful to visualize a few example images to understand the dataset:
import matplotlib.pyplot as plt
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.imshow(train_images[i], cmap='gray')
plt.title(class_names[train_labels[i]])
plt.axis('off')The images are 28×28 and somewhat blurry, but the model can still learn to classify them with high accuracy.
Next Steps (to be continued)
Further training with more epochs and regularization.
Handling color images (CIFAR-10, etc.) — rank-4 tensors.
Convolutional Neural Networks (CNNs) for better image classification.

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