1. Home
  2. Explore
  3. Computer Science
  4. Convolutional Neural Networks

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Convolutional Neural Networks

Convolutional Neural Networks – Comprehensive Study Notes

What Is Machine Learning?

Machine learning is a subdomain of computer science focused on algorithms that allow computers to learn from data without being explicitly programmed for every instruction. The goal is to train a computer to understand, comprehend, or draw conclusions from the data it is fed.

Types of Machine Learning

Supervised Learning

  • Uses labeled inputs – each input has a corresponding output label.

  • The computer is trained on data where humans have already assigned correct answers (e.g., pictures of cats, dogs, lizards with their names attached).

  • The model learns to map inputs to outputs based on these examples.

Unsupervised Learning

  • Uses unlabeled data; the computer must find patterns or groupings on its own.

  • Example: given many images of cats, dogs, and lizards, the model clusters similar images together without being told the category names.

Reinforcement Learning

  • An agent learns in an interactive environment by receiving rewards or penalties for its actions.

  • Analogous to training a dog: sitting earns a treat (reward), barking earns a scolding (penalty). The agent learns which actions lead to future rewards.


Supervised Learning in Depth

In supervised learning, we have:

  • Inputs (feature vectors) – each sample is a vector of numbers representing its characteristics.

  • Model – processes inputs and produces a prediction (output).

  • Output labels – the ground truth for each input.

Features: Qualitative vs Quantitative

Qualitative (categorical) data – finite number of categories or groups.

  • Nominal: no inherent order (e.g., country of residence, gender).

  • Ordinal: natural ordering (e.g., happiness rating 1–5, age group: infant, child, teenager, adult).

Quantitative (numerical) data – numerical values.

  • Discrete: countable values (e.g., number of Easter eggs in a basket: 0, 1, 2, …).

  • Continuous: any value in a range (e.g., length 5.289 feet, temperature 200°F).

Types of Predictions (Outputs)

Classification

  • Predict discrete classes.

  • Binary classification: two options (e.g., hot dog vs not hot dog, spam vs not spam, positive vs negative sentiment).

  • Multi-class classification: more than two categories (e.g., cat, dog, lizard; different types of food).

Regression

  • Predict a continuous value.

  • Examples: price of an asset (Ethereum), amount of snowfall, housing market price.

The Data Set: Feature Matrix and Targets

Consider the Pima Indian diabetes dataset:

  • Each row is a sample (one individual).

  • Each column (except the last) is a feature (e.g., number of pregnancies, glucose level, blood pressure, BMI, age).

  • The last column is the outcome label (1 = diabetes, 0 = no diabetes).

  • The collection of all feature vectors is the feature matrix XXX.

  • The collection of all outcome labels is the target vector yyy.

Key Terminology: XXX is the feature matrix, yyy is the target vector. The model takes a feature vector and predicts an output. The difference between prediction and true label is used to train the model.

Splitting Data: Training, Validation, Testing

To evaluate a model's performance on unseen data, the original dataset is split into three parts:

  • Training set: most of the data – used to train the model.

  • Validation set: a separate portion used to compare different models (like test-driving cars) and select the best one. Not used for final performance evaluation.

  • Test set: held aside entirely, used only once on the final chosen model to measure generalization ability – how well it performs on completely new data.


Loss Functions and Metrics

Loss

Loss measures how far the model's prediction is from the true label. A larger difference leads to a larger loss.

  • L1 loss (absolute error): penalty is linear – if prediction is 10 away, loss = 10.

  • L2 loss (squared error): penalty is quadratic – if prediction is 10 away, loss = 100. This penalizes large errors more heavily.

  • Binary cross-entropy loss: used for binary classification (hot dog/not hot dog). As the model improves, the loss decreases.

Accuracy

A simple performance metric: the fraction of correct predictions.

Accuracy=number of correct predictionstotal predictions\text{Accuracy} = \frac{\text{number of correct predictions}}{\text{total predictions}}Accuracy=total predictionsnumber of correct predictions​

Neural Networks

A neural network is a powerful model commonly used for classification and regression tasks. It consists of:

  • Input layer: the feature vector (vertical).

  • Hidden layers (nodes/neurons): each node receives weighted inputs, sums them, adds a bias, and applies an activation function.

  • Output layer: produces the final prediction.

How a Single Node (Neuron) Works

  1. Each input xix_ixi​ is multiplied by a weight wiw_iwi​ (determining importance).

  2. All weighted inputs are summed: ∑wixi\sum w_i x_i∑wi​xi​.

  3. A bias bbb is added (like an intercept).

  4. The sum is passed through an activation function fff to produce the node's output.

Without activation functions, the entire network collapses into a linear model (one coefficient per input). Activation functions introduce nonlinearity, allowing the network to learn complex patterns.

Common Activation Functions

Function

Shape

Description

Sigmoid

S-curve

Maps input to (0,1) – used for binary output probabilities.

Tanh

S-curve through origin

Maps input to (-1,1).

ReLU (Rectified Linear Unit)

f(x)=max⁡(0,x)f(x) = \max(0, x)f(x)=max(0,x)

Very commonly used; introduces nonlinearity simply.

ReLU is a classic default activation function.

Training: Gradient Descent and Backpropagation

Training adjusts the weights to minimize the loss.

  • Gradient descent: computes the slope (gradient) of the loss function at the current weight values, then takes a step in the direction that reduces loss.

  • Learning rate α\alphaα : a small positive number controlling step size (to avoid overshooting).

  • The weight update rule: wnew=wold−α⋅gradientw_{\text{new}} = w_{\text{old}} - \alpha \cdot \text{gradient}wnew​=wold​−α⋅gradient.

  • Backpropagation is the algorithm that calculates the gradient of the loss with respect to each weight in the network.

The goal is to find weight values that yield a low loss (close to zero), meaning predictions closely match actual labels.


Convolutional Neural Networks (CNNs)

CNNs are designed to process image data. Images are not naturally flat vectors – they are 2D arrays of pixels. CNNs extract meaningful features from images to feed into a regular neural network for classification.

Images as Numbers

  • An image is a grid of pixels.

  • Each pixel has a value from 0 (black) to 255 (white) for grayscale; color images have three channels (RGB).

  • A grayscale image is a 2D matrix; a color image is a 3D tensor (height × width × 3).

Convolution Layer

A convolution applies a small filter (also called a kernel) over the entire input image.

  • The filter is a small matrix (e.g., 3×3) that slides across the image, performing element-wise multiplication with the patch it covers and summing the results.

  • Each filter detects a specific feature (e.g., edges, corners, textures).

  • The output is a feature map (another 2D grid) highlighting where that feature appears.

Example: An edge-detection filter will produce a feature map showing edges in the original image.

During training, the network learns the optimal filter values (weights) to extract the most useful features for the task.

Pooling Layer

Pooling reduces the spatial size of the feature maps, making the network computationally efficient and more robust to small translations.

  • Max pooling: takes the maximum value from a small window (e.g., 2×2) and discards the rest.

  • Average pooling: takes the average instead.

Pooling condenses information, preserving the most important activations.

Typical CNN Architecture

  1. Input image (resized to square, e.g., 128×128×3)

  2. Convolution + activation (e.g., 128 filters, 3×3 kernel, ReLU)

  3. Max pooling (2×2)

  4. Convolution + activation (64 filters, 3×3, ReLU)

  5. Max pooling (2×2)

  6. Flatten – converts the 2D feature maps into a 1D vector

  7. Fully connected (dense) layers – regular neural network

  8. Output layer – e.g., 1 node for binary classification

These layers are stacked to form a feature extractor followed by a classifier.


Hands-On Example: Hot Dog vs Not Hot Dog Classifier

This example uses TensorFlow (an open-source machine learning library) and the Food‑101 dataset. The goal: build a CNN that distinguishes images of hot dogs from all other foods.

Step 1: Import Libraries

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import tensorflow_datasets as tfds

Step 2: Load and Explore Data

  • Load the food101 dataset using tfds.load().

  • The dataset comes with pre-split train and validation sets.

  • Hot dog is label 55.

  • Images are various sizes and shapes.

Step 3: Preprocessing

Resize and Binarize Labels

  • Resize all images to a fixed square size (e.g., 128×128) using tf.image.resize().

  • Convert the label: 1 if the food is a hot dog (label == 55), 0 otherwise.

  • Cast pixel values to tf.int32.

Balance the Dataset

  • The dataset has 750 hot dog images in training, 250 in validation.

  • To avoid huge class imbalance, upsample the hot dog class (repeat it three times) and then sample 50% from hot dogs and 50% from non-hot dogs using tf.data.Dataset.sample_from_datasets().

Batching and Performance

train_ds = train_ds.cache().batch(16).prefetch(tf.data.AUTOTUNE)
valid_ds = valid_ds.cache().batch(16).prefetch(tf.data.AUTOTUNE)
  • Cache: store dataset in memory for faster access.

  • Batch: feed 16 images at a time (batch size = 16).

  • Prefetch: overlap data loading with model training.

Step 4: Build the CNN Model

A tf.keras.Sequential model:

  1. Rescaling layer: divide pixel values by 255 to get range [0,1].

  2. Data augmentation (optional but recommended):

    • RandomFlip("horizontal")

    • RandomRotation(0.2)

  3. Convolution block 1:

    • Conv2D(128, (3,3), activation='relu', input_shape=(128,128,3))

    • MaxPooling2D((2,2))

    • Dropout(0.25) – randomly turns off 25% of connections to prevent overfitting.

  4. Convolution block 2:

    • Conv2D(64, (3,3), activation='relu')

    • MaxPooling2D((2,2))

    • Dropout(0.25)

  5. Flatten.

  6. Dense layer: Dense(128, activation='relu').

  7. Output layer: Dense(1) – no activation (logits) because we will use from_logits=True in the loss.

Regularization can be added with kernel_regularizer=tf.keras.regularizers.l2(0.01) to penalize large weight changes.

Step 5: Compile the Model

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
    loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
    metrics=['accuracy']
)
  • Adam optimizer: popular choice for adjusting weights.

  • Binary cross-entropy: appropriate for binary classification.

  • from_logits=True because the output layer uses raw scores (not probabilities).

Step 6: Train the Model

history = model.fit(
    train_ds,
    validation_data=valid_ds,
    epochs=50,
    verbose=1
)
  • An epoch = one complete pass through the training dataset.

  • Monitor training loss/accuracy and validation loss/accuracy.

Step 7: Analyze Training Results

After training (e.g., 50 epochs):

  • Training accuracy: may reach near 100%.

  • Validation accuracy: may plateau around 70–75%.

If training accuracy is high but validation accuracy is lower, the model is overfitting – it has memorized the training data but does not generalize well to new data.

Step 8: Improve Generalization (Mitigate Overfitting)

  • Data augmentation: adds diversity (random flips, rotations) so the model sees more varied examples.

  • Dropout layers: randomly drop connections during training.

  • Kernel regularizers: penalize large weights.

  • Reduce model capacity: fewer filters or smaller dense layers.

Step 9: Evaluate on Validation Set

Plot a few validation images alongside the model's predictions:

  • label = 1 means the model thinks it's a hot dog.

  • label = 0 means not a hot dog.

Compare with the true labels to see if the model correctly identifies hot dogs.

With the improvements, the model achieved around 70–75% accuracy on the validation set – a solid result given the challenge (many foods look similar to hot dogs).


Key Takeaways

  • Convolutional Neural Networks are powerful for image classification, using convolution and pooling to extract features and reduce dimensionality.

  • Supervised learning requires labeled data; the model learns from examples.

  • Neural networks learn through gradient descent and backpropagation, adjusting weights to minimize a loss function.

  • Preventing overfitting is crucial: use data augmentation, dropout, regularization, and proper data splitting.

  • TensorFlow and Keras provide high-level APIs to build and train CNNs efficiently.

  • A simple CNN can distinguish hot dogs from other foods with reasonable accuracy; further tuning can improve performance.


Core Concept: CNNs transform raw pixel images into a compact feature vector that a fully connected neural network can classify. The convolution filters learn to detect important patterns (edges, textures, shapes) while pooling layers reduce computational load and add translation invariance.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent