1. Home
  2. Explore
  3. Computer Science
  4. Neural Networks for Image Recognition

Study methods

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

Neural Networks for Image Recognition

Neural Networks: From Fruit Classification to Doodle Recognition

This set of notes covers the fundamental concepts of neural networks, starting from simple linear separators and building up to multi-layer networks trained with backpropagation. The journey includes hands-on experiments with various datasets: a synthetic fruit classification problem, the MNIST handwritten digits, Fashion-MNIST, Quick Draw doodles, and CIFAR-10 color images. Each step reveals design choices — activation functions, cost functions, gradient descent, data augmentation — that gradually improve network performance.


Introduction to the Problem

The goal is to teach a computer to recognize doodles and images. The approach explored here is neural networks — a class of machine learning models loosely inspired by biological neurons.

Earlier attempts with simple physics simulations failed (e.g., a stick creature that stretched its legs endlessly), but a neural network successfully learned to steer a simulated car by processing sensor inputs and using evolutionary selection. The real target is to build a network capable of classifying images: first handwritten digits (28×28 pixels), then articles of clothing (from Fashion-MNIST), then doodles of objects (10 categories from Quick Draw), and finally full-color 32×32 images (like CIFAR-10). The last task is significantly more complex and may require a convolutional neural network upgrade.


Basic Neural Network Concepts

A Simple Example: Poisonous Fruit Classification

Imagine a new fruit that is purple, spiky, and has orange spots. Some are poisonous. Two measurable attributes are spot size and spike length. By plotting known examples on a graph with these two axes, a decision boundary can separate safe from poisonous fruit.

If the data is linearly separable, a simple network can learn a straight-line boundary. The network has:

  • Two inputs: spot size (x1) and spike length (x2).

  • Two outputs: first output for "safe", second for "poisonous". (Multiple outputs are preferred because future problems will have more than two classes; the class with the highest output value is the prediction).

Each input is connected to each output by a weight that indicates the importance of that input for that output. The output value is computed as:

output1=x1⋅w11+x2⋅w21+bias1\text{output}_1 = x_1 \cdot w_{11} + x_2 \cdot w_{21} + \text{bias}_1output1​=x1​⋅w11​+x2​⋅w21​+bias1​
output2=x1⋅w12+x2⋅w22+bias2\text{output}_2 = x_1 \cdot w_{12} + x_2 \cdot w_{22} + \text{bias}_2output2​=x1​⋅w12​+x2​⋅w22​+bias2​

Adding biases allows shifting the decision boundary away from the origin, enabling correct positioning.

The Need for Hidden Layers and Activation Functions

If the fruit data is not linearly separable (e.g., safe fruits are surrounded by poisonous ones), a single-layer network with only weights and biases cannot produce a curved decision boundary. The solution is to insert a hidden layer between input and output. A hidden layer with multiple nodes (neurons) increases the network's capacity to represent non-linear boundaries.

However, simply adding hidden layers without non-linearity still yields only linear transformations. Each node must apply an activation function to its weighted input. The activation function introduces non-linearity, allowing the network to learn complex, curved decision boundaries.

Definition: An activation function takes the weighted input (stimulus) and produces an activation value (output). It mimics the firing of a biological neuron: if the stimulus is strong enough, the neuron fires (output ≈ 1); otherwise it stays quiet (output ≈ 0).

A simple step function would cause abrupt changes, making training unstable. A sigmoid function smooths the transition:

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}σ(z)=1+e−z1​

Its derivative is σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z) (1 - \sigma(z))σ′(z)=σ(z)(1−σ(z)), which is easy to compute and useful for backpropagation.

Other activation functions exist (e.g., tanh, ReLU), but sigmoid is a good starting point.


Training a Neural Network

Measuring Performance: The Cost Function

To train the network, we need a quantitative measure of how well it performs. The cost function (also called loss or error) quantifies the difference between the network’s predictions and the true labels.

For a single output node, the node cost is:

cost=(a−y)2\text{cost} = (a - y)^2cost=(a−y)2

where aaa is the actual output (after activation) and yyy is the expected target (0 or 1 in binary classification). Squaring ensures the cost is positive and emphasizes larger errors more.

For the whole network, the total cost for one data point is the sum of node costs over all output nodes:

C=∑j(aj−yj)2C = \sum_{j} (a_j - y_j)^2C=∑j​(aj​−yj​)2

The average cost over all training examples is:

Cˉ=1N∑i=1NC(i)\bar{C} = \frac{1}{N} \sum_{i=1}^{N} C^{(i)}Cˉ=N1​∑i=1N​C(i)

Training the network means finding the weights and biases that minimize this average cost.

Gradient Descent

Gradient descent is an iterative optimization algorithm used to minimize the cost function. The idea is to start with random weights and biases, then repeatedly move them in the direction that reduces the cost most steeply — i.e., opposite to the gradient of the cost with respect to each parameter.

For a simple one-variable function f(x)f(x)f(x), the slope (derivative) indicates the direction of steepest ascent. The update rule is:

xnew=xold−η⋅f′(x)x_{\text{new}} = x_{\text{old}} - \eta \cdot f'(x)xnew​=xold​−η⋅f′(x)

where η\etaη is the learning rate that controls step size.

Applying this to a neural network, we treat all weights and biases as variables. The gradient of the cost with respect to each weight tells us how sensitive the cost is to that weight. By subtracting the gradient (scaled by the learning rate) from the current weight, we move downhill in the cost landscape.

Key challenge: The cost landscape is high-dimensional (one dimension per parameter). Gradient descent works well in practice but may get stuck in local minima or saddle points. Mini-batch training and momentum help escape these.

Calculus for the Derivative (Optional Refresher)

Before implementing efficient gradient computation, it's helpful to understand analytic derivatives. For example:

f(x)=x2−3x+4f(x) = x^2 - 3x + 4f(x)=x2−3x+4

Using the limit definition of the derivative:

f′(x)=lim⁡h→0f(x+h)−f(x)h=2x−3f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h} = 2x - 3f′(x)=limh→0​hf(x+h)−f(x)​=2x−3

This gives the exact slope at any xxx, avoiding the need for numeric approximation (which requires multiple function evaluations).

For multi-variable functions, we compute partial derivatives. For example, for the cost C=(a−y)2C = (a - y)^2C=(a−y)2 with respect to aaa:

∂C∂a=2(a−y)\frac{\partial C}{\partial a} = 2(a - y)∂a∂C​=2(a−y)

Backpropagation: Efficient Gradient Computation

The naive way to compute gradients would be to nudge each weight individually and observe the cost change — that would require one forward pass per parameter, which is prohibitively slow for large networks.

Backpropagation solves this by computing all gradients with a single forward pass and a single backward pass. It relies on the chain rule from calculus.

Consider a tiny network: input → hidden node → output node. The weight w2w_2w2​ connects hidden activation a1a_1a1​ to output's weighted input z2z_2z2​. The cost CCC depends on w2w_2w2​ through the sequence:

C  depends on  a2  depends on  z2  depends on  w2C \; \text{depends on} \; a_2 \; \text{depends on} \; z_2 \; \text{depends on} \; w_2Cdepends ona2​depends onz2​depends onw2​

The chain rule gives:

∂C∂w2=∂C∂a2⋅∂a2∂z2⋅∂z2∂w2\frac{\partial C}{\partial w_2} = \frac{\partial C}{\partial a_2} \cdot \frac{\partial a_2}{\partial z_2} \cdot \frac{\partial z_2}{\partial w_2}∂w2​∂C​=∂a2​∂C​⋅∂z2​∂a2​​⋅∂w2​∂z2​​

Each of these derivatives is known:

  • ∂C∂a2=2(a2−y)\frac{\partial C}{\partial a_2} = 2(a_2 - y)∂a2​∂C​=2(a2​−y)

  • ∂a2∂z2=σ′(z2)=a2(1−a2)\frac{\partial a_2}{\partial z_2} = \sigma'(z_2) = a_2 (1 - a_2)∂z2​∂a2​​=σ′(z2​)=a2​(1−a2​) (for sigmoid)

  • ∂z2∂w2=a1\frac{\partial z_2}{\partial w_2} = a_1∂w2​∂z2​​=a1​ (the activation from previous layer)

Similarly, for a bias b2b_2b2​: ∂z2∂b2=1\frac{\partial z_2}{\partial b_2} = 1∂b2​∂z2​​=1

For weights in earlier layers, the same idea applies recursively, propagating "node values" (the product of cost derivative and activation derivative) backward through the network.

The backpropagation algorithm:

  1. Forward pass: Compute activations for all layers, storing weighted inputs and activations.

  2. Compute output error: For the output layer, calculate node values δj=∂C∂aj⋅σ′(zj)\delta_j = \frac{\partial C}{\partial a_j} \cdot \sigma'(z_j)δj​=∂aj​∂C​⋅σ′(zj​).

  3. Backward pass: For each hidden layer, compute its node values using the node values from the next layer and the connecting weights: δ(l)=(W(l+1))Tδ(l+1)⊙σ′(z(l))\delta^{(l)} = (W^{(l+1)})^T \delta^{(l+1)} \odot \sigma'(z^{(l)})δ(l)=(W(l+1))Tδ(l+1)⊙σ′(z(l)) (where ⊙\odot⊙ is element-wise multiplication).

  4. Gradient accumulation: For each weight wjkw_{jk}wjk​ connecting node kkk in layer l−1l-1l−1 to node jjj in layer lll, the gradient is ∂C∂wjk=ak(l−1)⋅δj(l)\frac{\partial C}{\partial w_{jk}} = a_k^{(l-1)} \cdot \delta_j^{(l)}∂wjk​∂C​=ak(l−1)​⋅δj(l)​. For biases, ∂C∂bj=δj(l)\frac{\partial C}{\partial b_j} = \delta_j^{(l)}∂bj​∂C​=δj(l)​.

  5. Update parameters: After accumulating gradients over a mini-batch, subtract them (scaled by learning rate) from the current weights and biases.

Mini-batch Gradient Descent

Instead of computing gradients on the entire dataset (full-batch) or a single example (stochastic), mini-batch gradient descent uses a small subset (e.g., 100 examples) per update. This speeds up training by making more frequent updates, and the noise helps escape poor local minima or saddle points. The learning rate must be tuned to balance convergence speed and stability.


Implementation Details

The code is structured around a Layer class and a NeuralNetwork class.

Layer Class

Each layer stores:

  • Weights: matrix of size num_incoming_nodes × num_outgoing_nodes

  • Biases: vector of size num_outgoing_nodes

  • Gradients: arrays for weight and bias gradients, accumulated during backpropagation

The calculate_output function computes weighted inputs and applies the activation function (e.g., sigmoid). During backpropagation, the layer stores intermediate values like weighted inputs (z) and activations (a).

NeuralNetwork Class

The network holds an array of layers. The classify function runs a forward pass and returns the index of the output node with the highest activation (i.e., the predicted class).

The learn function:

  1. Initializes gradients to zero.

  2. For each mini-batch, for each data point:

    • Forward pass to get activations.

    • Compute output node values.

    • Backward pass through layers to compute gradients.

    • Accumulate gradients (sum over mini-batch).

  3. Apply gradients: subtract learning rate times average gradient (divide by mini-batch size) from each weight and bias.

Performance Optimizations

  • Parallelization: The forward and backward passes can be vectorized (using matrix multiplication over multiple data points simultaneously) to speed computation.

  • Momentum: Adding a momentum term to gradient descent helps accelerate in consistent downhill directions and dampens oscillations. Update with momentum: v=μv−η∇Cv = \mu v - \eta \nabla Cv=μv−η∇C, then w=w+vw = w + vw=w+v, where μ\muμ is the momentum coefficient.

  • Learning rate tuning: A small learning rate leads to slow convergence; a large learning rate may cause divergence. Finding the right balance is critical.


Experiments with Different Datasets

Fruit Classification

First test with the two-dimensional synthetic fruit data. A network with 2 inputs, a hidden layer (e.g., 3 nodes), and 2 outputs (safe/poisonous) can learn a curved decision boundary. After training, the network correctly classifies all training samples.

Handwritten Digits (MNIST)

  • Dataset: 70,000 images of digits 0–9, each 28×28 pixels (784 inputs). Output: 10 nodes.

  • Network architecture: 784 inputs → hidden layer (e.g., 100 nodes) → 10 outputs. Sigmoid activation.

  • Training: Mini-batch size 100. Learning rate ~0.1–1.0 after data preprocessing.

  • Results: After a few epochs, test accuracy reaches ~95%. With tuning (different cost functions, activation functions, momentum), accuracy increases to ~97%.

Observations:

  • The network is very sensitive to how input digits are preprocessed (centered, scaled).

  • When drawing own digits freehand, the network often misclassifies them because they are not aligned like the training data.

  • Data augmentation (random rotations, scaling, shifting, added noise) solves this: train a new network on modified data. This reduces overfitting (accuracy on training data ~99% but test improves to ~98.5% after augmentation).

  • The network still has weaknesses: a slanted "1" may be confused with a "7", or a short horizontal line at the bottom of a "1" becomes a "2" if extended too far.

Fashion-MNIST

  • Dataset: 70,000 grayscale images of clothing (t-shirts, pullovers, sneakers, etc.), 28×28 pixels. Same format as MNIST but more challenging.

  • Results: Test accuracy ~89%. Reported human performance ~83%, so the network surpasses humans.

Quick Draw Doodles

  • Dataset: 345 categories of doodles. Here 10 categories selected: helicopter, house plant, cat, cruise ship, windmill, popsicle, tractor, umbrella, bicycle, octopus.

  • Network: Larger (more nodes and hidden layers) to handle 28×28 grayscale doodles.

  • Training with data augmentation (same transformations as digits).

  • Results: ~87% test accuracy.

  • Observations:

    • Best categories: popsicles, umbrellas, bicycles.

    • Worst: tractors, helicopters.

    • Network is sensitive to small changes: adding a line can switch prediction from helicopter to umbrella to tractor to cruise ship.

    • Emphasizing distinctive features (e.g., the rotor of a helicopter) improves reliability.

CIFAR-10 Color Images

  • Dataset: 60,000 color images (32×32 pixels, 32×32×3 = 3072 inputs), 10 classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck.

  • Complexity: Objects are not isolated; backgrounds and environments add noise.

  • Network: Same simple feedforward architecture (no convolutions).

  • Results: Test accuracy ~53% (roughly 5× better than random 10%, but still low).

  • Conclusion: Simple fully connected networks are insufficient for such complex tasks. Next step: upgrade to a convolutional neural network (CNN) which is designed to handle spatial patterns and translational invariance.


Conclusion

Starting from a simple two-input fruit classification problem, this journey built a foundational understanding of neural networks: weights, biases, activation functions, cost functions, gradient descent, backpropagation, and mini-batch training. Hands-on experimentation with increasingly complex datasets revealed the power and limitations of fully connected networks. While they achieve high accuracy on structured datasets like MNIST and Fashion-MNIST, and reasonable results on doodles, they struggle with natural images containing diverse backgrounds and object variations. The natural progression is to explore convolutional neural networks for improved performance on such tasks.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent