Building Keras Models


Building Keras Models

Simon
Alright, Hope, I think we have a packed episode today. We're going to walk through the whole process of building a neural network from scratch, using Keras and TensorFlow, and we'll even dip into computer vision.

Hope
That sounds like a lot, but let's start with the basics. Last time they covered the training loop: you have a network with weights and biases, you define a loss function to measure how wrong the predictions are, and then you use an optimizer to update those weights to minimize the loss.

Simon
Exactly. And the optimizer typically uses gradient descent, where you calculate the gradient of the loss with respect to all the weights by running every single data point through the network. That's called one epoch, and you only update the weights once per epoch.

Hope
But they moved on to something smarter: stochastic gradient descent, or SGD. Instead of using all data at once, you randomly pick a small batch of points, pretend that's your whole dataset for a moment, calculate the gradient, and update the weights immediately.

Simon
Right. That means you update the weights many times within a single epoch. For example, if you have 1,000 data points and a batch size of 32, you'll have about 31 batches, so 31 updates per epoch. And that actually works better, both in terms of speed and often in terms of generalization.

Hope
So let's clarify what an epoch means in SGD: it's one full pass through the entire training data, but you've broken that pass into batches. So after you've gone through all batches, you've completed one epoch.

Simon
And each batch you run through all the layers, get predictions, compute loss, and update weights. By the time the next batch comes in, the weights have already changed. That's the key advantage—you don't wait until you've seen every data point.

Hope
Now, with all this flexibility comes a risk: overfitting. If your model gets too complex—too many layers or neurons—it might memorize the training data instead of learning general patterns. They showed that classic curve: training error keeps going down, but validation error starts climbing again.

Simon
To combat that, they introduced early stopping. You set aside a validation set, and while training, you monitor the validation loss. The moment it starts to increase, you stop. Geoff Hinton called it a 'beautiful free lunch' because it costs almost nothing and helps a lot.

Hope
But before we train, we need to get our data into the right shape. And that means understanding tensors. Tensors are just generalizations of numbers, vectors, and matrices to higher dimensions. A scalar is rank 0, a vector rank 1, a matrix rank 2, and a color image with three channels is a rank 3 tensor.

Simon
And a video? That's rank 4—a list of color images. TensorFlow gets its name because tensors flow through the network. It handles automatic gradient computation, gives you optimizers like Adam, and can even distribute work across GPUs or TPUs seamlessly.

Hope
Then on top of TensorFlow sits Keras, which makes life much easier. You get nice abstractions like layers, activation functions, and easy ways to preprocess data, train, and evaluate. They used the functional API in the lecture, which they say is flexible enough for pretty much anything.

Simon
Let's walk through the heart disease example. The dataset had 303 patients with features like age, cholesterol, and a target of 0 or 1. They split the data into 80% training and 20% test, and they did that before any normalization.

Hope
Important point: if you normalize using statistics from the whole dataset, information from the test set leaks into the training process. So split first, then compute mean and standard deviation only from the training set, and use those to normalize both training and test sets.

Simon
For categorical variables like 'thal', they used one-hot encoding. For numeric variables, they standardized them to have zero mean and unit variance. After that, they converted the Pandas dataframe to NumPy arrays and separated the features and target.

Hope
The network architecture was simple: an input layer of 29 nodes (one for each feature), a hidden dense layer with 16 neurons using ReLU activation, and an output layer with a single sigmoid neuron for binary classification. That gave 497 parameters.

Simon
Let's check: 29 inputs times 16 hidden neurons plus 16 biases gives 480, and 16 hidden to 1 output plus 1 bias gives 17. Total 497. They compiled the model with binary crossentropy loss, Adam optimizer, and accuracy as a metric.

Hope
Then they trained for 300 epochs with a batch size of 32 and a validation split of 20% from the training set. That means 193 training samples after removing 20% for validation, which gives 6 full batches of 32 and one tiny batch of 1—so 7 batches per epoch.

Simon
After training, they plotted the loss and accuracy curves. The training loss kept decreasing, but the validation loss flattened and then rose slightly—a sign of overfitting. The accuracy, however, kept improving even at the end, so they decided it was acceptable.

Hope
On the test set, which they had kept completely untouched, the model achieved 83.6% accuracy. That's much better than the baseline of always predicting 0, which would give 72.6% because the dataset is imbalanced.

Simon
Now, they switched gears to computer vision. Images are just grids of pixels. For grayscale, each pixel has an intensity from 0 to 255. For color, you have three channels: red, green, blue. So a color image is a rank 3 tensor: height x width x channels.

Hope
The classic task is image classification. They introduced Fashion-MNIST: 70,000 grayscale images of clothing, 28x28 pixels, across 10 classes. To use a standard neural network, you need to flatten each 28x28 image into a 784-element vector.

Simon
Then you feed that vector into a hidden layer with 256 ReLU neurons. But the output is different—you have 10 classes, so you need 10 output probabilities that sum to 1. That's where the softmax activation comes in: it exponentiates the outputs and divides by their sum.

Hope
And the loss function depends on how the labels are encoded. If they're given as integers 0-9, use sparse categorical crossentropy. If they're one-hot encoded, use categorical crossentropy. For binary, it's binary crossentropy. So choose accordingly.

Simon
Keras actually bundles Fashion-MNIST as a built-in dataset, already split into train and test. That's convenient for benchmarking. They loaded it, inspected a few images, and then we'll see next time how to actually build and train that model.

Hope
This episode covered a lot: from the training loop and SGD to preprocessing, overfitting, and even the basics of computer vision. It's a solid foundation for actually building and training your own neural networks.

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