ROB-330 · Lesson 9 of 12 · 31 min

Learning-based perception I: classification and convolutional networks

The methods in lessons 4 to 8 are designed by hand: an engineer decides that corners matter and writes a formula to find them. That works well for geometry, but recognizing what something is, a ripe strawberry, a damaged parcel, a person stepping into an aisle, depends on appearance in ways too varied to write down. Since 2012, when a convolutional neural network called AlexNet cut the error rate of the ImageNet image-classification benchmark nearly in half, learned models have dominated recognition. Robots now use them for classification, detection, segmentation, depth, keypoints and even direct control. This lesson explains how convolutional networks work, how they are trained and evaluated, and what a robotics engineer needs to know to use them responsibly. Lesson 10 builds on it for detection and segmentation.

From features to learned features

A classifier maps an input, here an image, to one of K classes. The classical approach computes hand-designed features (colour histograms, gradient histograms such as HOG, SIFT descriptors pooled into a 'bag of words') and trains a simple classifier on them, such as a support vector machine. Deep learning instead learns the features and the classifier together from labelled examples, by adjusting millions of parameters to reduce a loss function. Given enough representative data, learned features consistently outperform hand-designed ones on recognition, and they adapt to whatever the task needs.

The building block is the artificial neuron: a weighted sum of inputs plus a bias, passed through a non-linear activation function. The most common activation is the rectified linear unit, \( \text{ReLU}(x) = \max(0, x) \), which is cheap and keeps gradients from vanishing in deep networks. Layers of neurons stacked in sequence form a network; without the non-linearities, any stack of linear layers would collapse to a single linear map.

Convolutional layers

A fully connected layer joins every input to every output, which is wasteful for images: a 224 × 224 × 3 input connected to just 1,000 neurons needs 150 million weights. Convolutional layers exploit two properties of images. Locality: nearby pixels are related, so each output looks only at a small window. Translation equivariance: a pattern means the same thing wherever it appears, so the same weights are applied at every position. A convolutional layer is therefore a bank of learned filters, exactly the kernels of lesson 4, except that the network chooses their weights. Each filter spans all input channels and produces one output channel, a feature map.

For an input of width W, kernel size k, padding p and stride s, the output width is

\[W_{out} = \left\lfloor \frac{W - k + 2p}{s} \right\rfloor + 1\]

and a layer with \( C_{in} \) input channels and \( C_{out} \) filters of size k × k has \( (k^2 C_{in} + 1)\,C_{out} \) parameters, independent of image size. Pooling layers (for example 2 × 2 max pooling) or strided convolutions halve the resolution between stages, so deeper layers see larger regions of the image, their receptive field, and respond to larger, more abstract patterns. Early layers learn edge and colour detectors very like Gabor filters; middle layers respond to textures and parts; late layers respond to whole objects. A final global average pool and fully connected layer produce one score per class, and the softmax function turns scores \( z_k \) into probabilities:

\[p_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}\]

Worked problem

Output size and parameter count

A 224 × 224 × 3 image passes through a convolutional layer with 64 filters of size 7 × 7, stride 2 and padding 3. What is the output size, and how many parameters does the layer have?

Show solution
  1. Width: \( \lfloor (224 - 7 + 6)/2 \rfloor + 1 = \lfloor 111.5 \rfloor + 1 = 112 \).
  2. Output: 112 × 112 × 64.
  3. Parameters: \( (7^2 \times 3 + 1) \times 64 = 148 \times 64 = 9{,}472 \).

Answer: A 112 × 112 × 64 feature map from just 9,472 parameters, compared with billions for a fully connected layer of the same output size. This is the first layer of the widely used ResNet design.

A left-to-right diagram of a small convolutional network. An input image block labelled 224 by 224 by 3 feeds a series of progressively smaller but deeper blocks labelled conv and pool stages: 112 by 112 by 64, 56 by 56 by 128, 28 by 28 by 256, 14 by 14 by 512, then a thin bar labelled global average pool, then a short fully connected layer and a softmax column of class probabilities. Labels underneath say edges and colours, textures and parts, object parts, objects.
A convolutional network shrinks spatial resolution while increasing the number of feature channels, from edges to whole objects

Important architectures include VGG (2014), ResNet (2015), whose residual skip connections made networks of 50 to 150 layers trainable, MobileNet and EfficientNet, designed for phones and embedded robots, and vision transformers (ViT, 2020), which split the image into patches and use attention instead of convolution. At the time of writing, both convolutional and transformer backbones are in wide use, and large self-supervised backbones such as DINOv2 provide general-purpose features that work well with little task-specific data.

Training

Training adjusts the parameters θ to minimize a loss averaged over labelled examples. For classification the loss is the cross-entropy between the predicted probabilities and the true class y, \( L = -\log p_y \): near zero when the network is confidently right and large when it is confidently wrong. Backpropagation computes the gradient of the loss with respect to every parameter by the chain rule, and stochastic gradient descent (or a variant such as Adam) takes a small step against it on a random mini-batch of examples, repeating for many passes (epochs) through the data.

The central danger is overfitting: a large network can memorize its training images and still fail on new ones. The defences are standard practice.

  • Split the data into training, validation and test sets, with the test set touched only once at the end. Split by scene, robot run or day, not by random frame, because consecutive video frames are nearly identical and leak information between sets.
  • Data augmentation: random crops, flips, rotations, colour jitter, blur and noise teach invariance to changes the robot will meet.
  • Regularization: weight decay, dropout and early stopping when validation loss stops improving.
  • Transfer learning: start from a backbone pre-trained on a large dataset and fine-tune on the task. A few hundred labelled images per class often suffice this way, versus hundreds of thousands from scratch.
A tiny classifier trained by gradient descent on synthetic images, with a confusion matrix, precision and recall
import numpy as np
rng = np.random.default_rng(4)

def make(n):
    """8 x 8 images: class 1 has a vertical bar (a 'pin'), class 0 a horizontal bar, with noise."""
    X = rng.normal(0, 0.35, (n, 8, 8)); y = rng.integers(0, 2, n)
    for i in range(n):
        k = rng.integers(1, 7)
        if y[i]: X[i, :, k] += 1.0
        else:    X[i, k, :] += 1.0
    return X.reshape(n, 64), y

Xtr, ytr = make(600); Xte, yte = make(400)

# one learned 'filter' per pixel: logistic regression trained by gradient descent
w = np.zeros(64); b = 0.0; lr = 0.1
for epoch in range(300):
    p = 1 / (1 + np.exp(-(Xtr @ w + b)))
    g = p - ytr                                  # gradient of cross-entropy w.r.t. scores
    w -= lr * Xtr.T @ g / len(ytr); b -= lr * g.mean()

def evaluate(X, y):
    pred = (1 / (1 + np.exp(-(X @ w + b)))) > 0.5
    tp = int(((pred == 1) & (y == 1)).sum()); fp = int(((pred == 1) & (y == 0)).sum())
    fn = int(((pred == 0) & (y == 1)).sum()); tn = int(((pred == 0) & (y == 0)).sum())
    return tp, fp, fn, tn

tp, fp, fn, tn = evaluate(Xte, yte)
print("test confusion: TP=%d FP=%d FN=%d TN=%d" % (tp, fp, fn, tn))
print("accuracy %.3f, precision %.3f, recall %.3f" % ((tp + tn) / len(yte), tp / (tp + fp), tp / (tp + fn)))
Wimg = w.reshape(8, 8)
print("mean weight, top and bottom rows (cols 1-6): %+.3f" % Wimg[[0, 7], 1:7].mean())
print("mean weight, left and right columns (rows 1-6): %+.3f" % Wimg[1:7, [0, 7]].mean())
print("mean weight, interior pixels: %+.3f" % Wimg[1:7, 1:7].mean())
Output
test confusion: TP=164 FP=22 FN=34 TN=180
accuracy 0.860, precision 0.882, recall 0.828
mean weight, top and bottom rows (cols 1-6): +0.569
mean weight, left and right columns (rows 1-6): -0.604
mean weight, interior pixels: +0.008

The weights reveal how this simple model decides. Because bars never sit on the outer rows or columns, a vertical bar always reaches the top and bottom edges and a horizontal bar always reaches the left and right edges. The model learned to look there, with positive weights on the top and bottom rows and negative weights on the side columns, rather than recognizing 'bar-ness' everywhere. That is a small example of shortcut learning: networks exploit whatever pattern separates the training classes, which may not be the pattern the engineer intended. A real camera image of a pin cropped differently would fool it, which is exactly why test data must come from conditions the robot will really meet. A convolutional network with several filters and pooling would instead learn local oriented-bar detectors that work anywhere in the image.

Measuring performance

Accuracy, the fraction classified correctly, is misleading when classes are unbalanced or errors have different costs, which is almost always true in robotics. A safety classifier that never reports a person in an aisle that is empty 99 % of the time is 99 % accurate and useless. Use the confusion matrix and the measures built from it:

\[\text{precision} = \frac{TP}{TP + FP}, \qquad \text{recall} = \frac{TP}{TP + FN}\]

Precision asks what fraction of positive reports were right; recall asks what fraction of real positives were found. Raising the decision threshold usually trades recall for precision, and the right operating point depends on cost: a weed-spraying robot might prefer high precision (do not spray crops), while a person detector for a safety stop needs very high recall (never miss a person), accepting some false stops. The F1 score, the harmonic mean of the two, summarizes both. Calibration also matters: a network's softmax output of 0.9 is often not a 90 % probability of being right, and techniques such as temperature scaling can correct it so downstream decisions can use the confidence meaningfully.

Worked problem

Precision and recall from a confusion matrix

A fruit-picking robot's ripeness classifier is tested on 500 strawberries: 300 ripe and 200 unripe. It labels 280 as ripe, of which 260 really are ripe. Compute accuracy, precision and recall for the class ripe.

Show solution
  1. TP = 260; FP = 280 − 260 = 20; FN = 300 − 260 = 40; TN = 200 − 20 = 180.
  2. Accuracy: \( (260 + 180)/500 = 0.88 \).
  3. Precision: \( 260/280 = 0.929 \). Recall: \( 260/300 = 0.867 \).

Answer: Accuracy 88 %, precision 93 % (few unripe berries get picked) and recall 87 % (13 % of ripe berries are left behind). Whether to shift the threshold depends on the cost of each kind of error.

Worked problem

Softmax probabilities

A network outputs scores (2.0, 1.0, 0.1) for the classes box, bag and envelope. What probabilities does softmax give?

Show solution
  1. Exponentials: \( e^{2.0} = 7.389 \), \( e^{1.0} = 2.718 \), \( e^{0.1} = 1.105 \); sum 11.212.
  2. Probabilities: \( 0.659, 0.242, 0.099 \).

Answer: About 66 % box, 24 % bag and 10 % envelope. Whether 66 % is trustworthy depends on how well the network is calibrated.

Using learned models on robots

Deploying a network on a robot raises engineering questions beyond accuracy. Inference must fit the latency budget of ROB-320 on the available hardware: an embedded GPU module, a neural accelerator or a CPU. Models are typically exported to ONNX and optimized with tools such as TensorRT or OpenVINO, often with 8-bit integer quantization that cuts memory and time by two to four times for a small accuracy loss. Inputs must be pre-processed exactly as in training: the same resizing, normalization and colour order (RGB versus BGR is a classic bug). And the robot's environment will differ from the training data, a problem called distribution shift: new lighting, new products, dirty lenses, seasons. Monitoring confidence, logging hard cases, and periodically retraining on data from the field are part of operating a learned perception system, as is keeping a non-learned safety layer, such as a certified safety scanner, for functions where a missed detection could injure someone.

Worked problem

Fitting inference into the budget

A classifier takes 38 ms per image in 32-bit floating point on a robot's embedded GPU, and the control loop needs results at 30 Hz with at most 25 ms for inference. INT8 quantization is expected to give a 2.5× speed-up. Does it fit?

Show solution
  1. Frame period at 30 Hz: 33.3 ms, but inference is allowed 25 ms.
  2. FP32: 38 ms, too slow.
  3. INT8: \( 38/2.5 = 15.2 \) ms, within the 25 ms budget.

Answer: Yes, after quantization, with about 10 ms to spare, provided accuracy on a validation set from the robot's own cameras stays acceptable.

Common mistakes

  • MistakeSplitting video frames randomly into training and test sets

    InsteadSplit by scene, run or day so near-identical frames do not leak between sets.

  • MistakeReporting accuracy alone on unbalanced or safety-critical data

    InsteadReport precision, recall and the confusion matrix, and choose the threshold by the costs of each error.

  • MistakeTreating softmax outputs as calibrated probabilities

    InsteadCheck calibration on validation data and apply temperature scaling if needed.

  • MistakePre-processing images differently at deployment than in training

    InsteadMatch resizing, normalization and channel order exactly.

  • MistakeRelying on a learned detector as the only protection for people

    InsteadKeep a certified, non-learned safety function for safety-critical detection.

Summary and key terms

  • Deep networks learn features and classifiers together from labelled data, outperforming hand-designed features on recognition.
  • Convolutional layers apply learned filters across the image, with output size \( \lfloor (W - k + 2p)/s \rfloor + 1 \) and few parameters.
  • Deeper layers have larger receptive fields and respond to more abstract patterns; softmax turns scores into probabilities.
  • Training minimizes cross-entropy with backpropagation and stochastic gradient descent.
  • Proper data splits, augmentation, regularization and transfer learning guard against overfitting.
  • Precision, recall and calibrated confidence matter more than accuracy for robot decisions.
  • Deployment needs optimization for latency, matched pre-processing, monitoring for distribution shift and non-learned safety layers.
Convolutional neural network
A network built mainly from learned convolution filters.
Feature map
The output channel produced by one convolutional filter.
Receptive field
The region of the input image that affects a given neuron.
ReLU
The activation function max(0, x).
Softmax
A function turning class scores into probabilities that sum to one.
Cross-entropy loss
The negative log of the probability assigned to the true class.
Backpropagation
Computing gradients of the loss through the network by the chain rule.
Overfitting
Fitting training data so closely that performance on new data suffers.
Transfer learning
Fine-tuning a network pre-trained on a large dataset for a new task.
Distribution shift
A difference between training data and the data met in deployment.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Output width for W = 32, k = 3, p = 1, s = 1?

    Show answer

    32.

  2. Parameters in a 3 × 3 convolution from 16 to 32 channels?

    Show answer

    \( (9 \times 16 + 1) \times 32 = 4{,}640 \).

  3. What does ReLU output for an input of −2.5?

    Show answer

    0.

  4. TP = 45, FP = 5: what is precision?

    Show answer

    0.9.

  5. TP = 45, FN = 15: what is recall?

    Show answer

    0.75.

  6. Which metric matters most for a safety person detector?

    Show answer

    Recall.

  7. Name two data augmentations.

    Show answer

    Random crops, flips, rotations, colour jitter, blur or noise.

  8. Why split robot video by run rather than by frame?

    Show answer

    Adjacent frames are nearly identical and leak into the test set.

  9. What does INT8 quantization trade for speed?

    Show answer

    A small loss of accuracy.

  10. What is distribution shift?

    Show answer

    Deployment data differing from training data.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz