Building and Training Neural Networks

7 min read

Welcome back, developer! 🧠

In the previous modules, you acted like a digital architect. You designed the structure of a neural network—stacking layers like LEGO bricks. You compiled it with an optimizer (the teacher) and a loss function (the score sheet).

But right now? Your model is like a newborn baby. It has the capacity to learn, but it knows absolutely nothing. Its weights are initialized with random garbage numbers. If you asked it to classify a cat right now, it might tell you it's a toaster with 50% confidence.

In this guide, we are going to send this model to the gym. We are going to feed it data, sweat through the math, and turn it into a prediction machine.


1. The Training Loop: fit() and evaluate()

The Problem

You have a compiled model and a dataset (Inputs X and Labels y). How do you mechanically connect the two so the optimizer can start tweaking those weights to minimize loss?

The Solution: model.fit()

In TensorFlow (Keras), the magic happens inside the .fit() method. This function initiates the training loop. It takes the input data, passes it through the network, compares the output to the actual labels, calculates the error, and backpropagates that error to adjust the weights.

It’s called fit because we are "fitting" a curve (or a hyper-plane) to our data points.

Basic Usage

python
import tensorflow as tf

# Let's assume you have your data prepared
# x_train: Input images (normalized)
# y_train: Correct labels (0-9)

# Standard training call
history = model.fit(
    x=x_train, 
    y=y_train, 
    epochs=5, 
    batch_size=32
)

What is history?
The .fit() method doesn't just run; it returns a History object. This object contains a dictionary (history.history) storing the loss and accuracy values for every single epoch. This is crucial for plotting graphs later to see if your model is actually getting smarter or just guessing.

The Solution: model.evaluate()

Once training is done, you cannot trust your model yet. Why? Because it has seen the training data thousands of times. It might have just memorized the answers (we'll discuss overfitting in a bit).

You need to test it on data it has never seen before. This is where .evaluate() comes in.

python
# Returns [loss, accuracy] (depending on your metrics)
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)

print(f'\nTest accuracy: {test_acc}')

Industry Tip: Never, ever train on your test data. If you do, that's called "Data Leakage." It’s like stealing the exam paper before the test. You’ll get 100%, but you won't know anything.


2. Understanding Epochs, Batch Size, and Steps per Epoch

The Problem

Why can't we just dump 100GB of data into the model instantly?

  1. RAM Limitations: Your computer (or GPU) will explode.
  2. Learning Stability: Updating weights based on all data at once is actually less efficient for finding the global minimum than doing it in small chunks.

We need to break the learning process down.

The Concepts

📦 Batch Size

This is the number of samples the model works through before updating its internal model parameters.

  • Definition: A subset of your training data.
  • How it works: If you have 1,000 images and a batch_size of 100, the model looks at the first 100 images, calculates the average error, updates the weights, and moves to the next 100.
  • Industry Standard: usually powers of 2 (32, 64, 128, 256).
    • Small Batch (e.g., 32): Less memory, noisier updates (can help jump out of local minima), slower per epoch but converges faster in terms of updates.
    • Large Batch (e.g., 1024): Faster computation (GPU parallelism), but requires huge RAM and might get stuck in local minima.

🔄 Epochs

An epoch is one complete pass through the entire training dataset.

  • Definition: Total Samples / Batch Size iterations.
  • Why more than 1? Seeing the data once isn't enough. The optimizer takes small steps. It needs to see the same data multiple times to refine the weights.
  • Fun Fact: If you set epochs=1000 on a complex model, you have time to go make coffee, drink the coffee, roast new beans, and make coffee again.

👣 Steps Per Epoch

This is usually calculated automatically by TensorFlow, but you should know the math.

Steps=Total Training SamplesBatch Size\text{Steps} = \frac{\text{Total Training Samples}}{\text{Batch Size}}

If you have 60,000 images and a batch size of 64:

60,000/64=937.5≈938 steps60,000 / 64 = 937.5 \approx 938 \text{ steps}

The progress bar you see during training represents these steps.

Real Life Simulation 📚

Imagine you are studying for a History exam with 1,000 flashcards.

  • Batch Size: You grab 10 cards, read them, quiz yourself, and then check the textbook to correct your understanding.
  • Epoch: You have successfully gone through all 1,000 cards once.
  • Training: You repeat the whole stack (Epochs) 10 times until you stop making mistakes.

3. Managing Overfitting, Underfitting, and Validation Data

The Problem

  • Underfitting: Your model is too simple (or not trained enough). It’s like using a linear ruler to draw a circle. It fails on training data and test data.
  • Overfitting: Your model is too complex (or trained too long). It memorizes the training data noise rather than the signal. It gets 99% accuracy on training data but fails miserably on new data.

The Solution: Validation Data

We split our data into three parts:

  1. Training: For learning (The Textbook).
  2. Validation: For tuning during training (The Practice Quiz).
  3. Test: For final evaluation (The Final Exam).

You can pass validation data directly into .fit() to monitor performance in real-time.

python
history = model.fit(
    x_train, 
    y_train, 
    epochs=20,
    batch_size=64,
    # Reserve 20% of training data for validation automatically
    validation_split=0.2 
)

Visualizing the Problem

You must look at the loss curves.

  • If Training Loss goes down but Validation Loss goes UP... STOP! You are overfitting. 🛑

Industry Solution: Early Stopping

Instead of guessing how many epochs you need (Is it 50? Is it 100?), use a callback to stop training automatically when the validation loss stops improving.

python
callback = tf.keras.callbacks.EarlyStopping(
    monitor='val_loss',
    patience=3, # Wait 3 epochs to see if it improves
    restore_best_weights=True # Go back to the best version
)

model.fit(..., callbacks=[callback])

This is the most "bang for your buck" technique to instantly improve model reliability.


4. Making Predictions and Interpreting Output Probabilities

The Problem

You trained the model. It has 98% accuracy. Great. Now, how do you actually use it to identify the image uploaded by a user?

The Solution: model.predict()

This method takes input data and returns the raw output of the last layer.

python
# X_new is a new image the model hasn't seen
predictions = model.predict(x_new)

Interpreting the Output

If your last layer is a Dense layer with softmax activation (common for classification), the output will be an array of probabilities that sum to 1.0.

Example output for a cat/dog/bird classifier:
[0.05, 0.94, 0.01]

  • Index 0 (Cat): 5%
  • Index 1 (Dog): 94%
  • Index 2 (Bird): 1%

To get the actual class label (the winner), you use numpy or tensorflow:

python
import numpy as np

# Get the index of the highest probability
predicted_class = np.argmax(predictions[0]) 
# Returns 1 (Dog)

⚠️ Logits vs. Probabilities

If your model output layer does not have an activation function (often done for numerical stability when using from_logits=True in loss functions), model.predict() will return Logits (raw scores, can be negative or greater than 1).

You must pass them through Softmax to understand them as percentages.

python
probability_model = tf.keras.Sequential([
  model,
  tf.keras.layers.Softmax()
])
predictions = probability_model.predict(x_test)

Pro Tip: Just because a model says "99% confident" doesn't mean it's right. Neural networks can be "confidently wrong" about images that look like static noise. Always validate predictions in high-stakes environments.


📚 References & Further Reading

“I fear not the man who has practiced 10,000 epochs once, but I fear the man who has practiced one epoch 10,000 times... wait, actually both of those are terrible training strategies.” — Bruce Lee (probably not).

Challenge

Challenge: Implementing the Full Training and Evaluation Workflow

You are provided with a pre-defined and compiled Keras model and mock datasets: x_train, y_train, x_val, y_val, x_test, and y_test.

Your task is to implement the complete training, validation, and evaluation pipeline using TensorFlow/Keras, incorporating best practices to prevent overfitting.

Instructions:

  1. Import the EarlyStopping callback from tensorflow.keras.callbacks.
  2. Instantiate the EarlyStopping callback. It should monitor val_loss, stop training if there is no improvement after 5 epochs (patience), and be configured to restore the model weights from the epoch with the best value of the monitored quantity.
  3. Train the model by calling its fit() method. Use the x_train and y_train data. The training should be set for a maximum of 50 epochs with a batch_size of 64.
  4. Crucially, during the training process, use the validation data (x_val, y_val) to monitor for overfitting and pass your EarlyStopping callback to the fit method.
  5. After the training is complete, evaluate the model's final performance on the completely unseen x_test and y_test data. Store the results in a variable named test_metrics.
  6. Use the trained model to make a prediction on the first sample of the test set (x_test[0]). Store the raw probability array output in a variable named raw_prediction.
  7. Using numpy, find the index of the most likely class from raw_prediction and store it in a variable named predicted_class.

Expected result

Your solution should contain the following implementations:

  • An import statement for EarlyStopping from tensorflow.keras.callbacks.
  • An instance of EarlyStopping assigned to early_stopping_callback. This instance must be configured to monitor 'val_loss', with patience=5, and restore_best_weights=True.
  • A call to model.fit() assigned to the history variable. The call must include:
    • x_train and y_train as the training data.
    • epochs=50
    • batch_size=64
    • The validation_data parameter set to the tuple (x_val, y_val).
    • The callbacks parameter set to a list containing your early_stopping_callback instance.
  • A call to model.evaluate() using x_test and y_test as arguments, with its return value assigned to test_metrics.
  • A call to model.predict() on the first sample of the test set. Because the model expects a batch, the input should be shaped correctly, for example, x_test[0:1] or np.expand_dims(x_test[0], axis=0). The result should be assigned to raw_prediction.
  • A call to np.argmax() on the raw_prediction variable to get the index of the highest value, with the result assigned to predicted_class.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.