Module 4/5 · Weeks 10–12 · 27 h

Deep learning and object detection

UAT 306 Artificial Intelligence for UAS

About 90 minDraft, awaiting reviewLast updated 24 October 2026

Lesson

By the end of this module you will be able to

  1. Explain a neuron, layers and backpropagation, and compute one gradient step by hand
  2. Compute the output size and parameter count of convolution layers
  3. Explain how an object detector predicts both class and location
  4. Write non-maximum suppression to remove duplicate boxes
  5. Compute a detector's precision, recall and average precision

Prerequisites: UAT 306 Modules 1–3

Why this matters

A detector must predict both the type and the location of objects, IoU matches predictions to answers, and mAP combines ranking with several conditions. This module computes these key pieces by hand, step by step, so that the output of tools such as Ultralytics YOLO can be read with understanding.

Neurons, layers and backpropagation

An artificial neuron computes a weighted sum of its inputs plus a bias, , and passes it through an activation function such as the sigmoid, tanh or ReLU (). Logistic regression in Module 2 is exactly one neuron with a sigmoid. A neural network stacks neurons in layers: the outputs of one layer are the inputs of the next, and the layers between input and output are called hidden layers. Without a nonlinear activation, stacked layers would collapse into one linear model; with it, a network with enough hidden neurons can represent curved decision boundaries (Goodfellow et al., 2016, chapter 6).

Training needs the gradient of the loss with respect to every weight. Backpropagation (Rumelhart, Hinton and Williams, 1986) computes all of them efficiently: first a forward pass computes every layer’s output and the loss; then a backward pass starts from the error at the output and applies the chain rule of calculus layer by layer back towards the input, reusing the values from the forward pass. Gradient descent then updates every weight as in Module 2.

Example 1 One neuron by hand, then a small network that one neuron cannot replace

By hand. A neuron with weights , bias and a sigmoid receives the patch features , and the correct answer is .

  • Forward: , so and the loss is
  • Backward: for a sigmoid with cross-entropy, ; by the chain rule and
  • Update with : and , which raises towards 1

A network. Patches of sound concrete cluster in the middle of two standardised features (brightness and texture), and defects lie around them in every direction (400 simulated patches). No straight line can separate a ring, so we compare one neuron with a network of one hidden layer of 8 tanh neurons, both trained by gradient descent; the network’s gradients come from backpropagation written by hand.

import numpy as np

rng = np.random.default_rng(0)
n = 400
X = rng.uniform(-1, 1, (n, 2))                          # two standardised patch features
y = (np.hypot(X[:, 0], X[:, 1]) < 0.6).astype(float)[:, None]   # 1 = sound concrete (centre cluster)

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

# a single neuron (logistic regression) for comparison
w, b = np.zeros((2, 1)), 0.0
for _ in range(3000):
    p = sigmoid(X @ w + b)
    w -= 0.5 * X.T @ (p - y) / n
    b -= 0.5 * float(np.mean(p - y))
print(f"single neuron: accuracy {((p > 0.5) == y).mean():.2f}")

# a network with one hidden layer of 8 neurons
W1, b1 = rng.normal(0, 1, (2, 8)), np.zeros(8)
W2, b2 = rng.normal(0, 1, (8, 1)), np.zeros(1)
for it in range(1, 3001):
    h = np.tanh(X @ W1 + b1)                            # forward: hidden layer
    p = sigmoid(h @ W2 + b2)                            # forward: output neuron
    d2 = (p - y) / n                                    # backward: error at the output
    d1 = (d2 @ W2.T) * (1 - h ** 2)                     # backward: chain rule through tanh
    W2 -= 0.5 * h.T @ d2
    b2 -= 0.5 * d2.sum(axis=0)
    W1 -= 0.5 * X.T @ d1
    b1 -= 0.5 * d1.sum(axis=0)
    if it in (1, 300, 3000):
        loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
        print(f"hidden-layer network, iteration {it:>4}: loss {loss:.3f}, accuracy {((p > 0.5) == y).mean():.2f}")
print("parameters:", W1.size + b1.size + W2.size + b2.size)
single neuron: accuracy 0.71
hidden-layer network, iteration    1: loss 0.979, accuracy 0.47
hidden-layer network, iteration  300: loss 0.192, accuracy 0.97
hidden-layer network, iteration 3000: loss 0.048, accuracy 0.98
parameters: 33

The single neuron reaches only 0.71, about the share of the larger class (defects make up 71.5% of the patches), because it can only draw a straight line. The hidden-layer network, with just 33 parameters, learns the round boundary and reaches 0.98. The two lines marked “backward” are the whole of backpropagation for this network: the output error is passed back through the output weights and multiplied by the derivative of tanh, .

Convolution layers

A convolution layer slides a filter over the image, and the accumulated products form a feature map. The output size depends on the input size , kernel size , padding and stride , following the formula in A guide to convolution arithmetic (Dumoulin and Visin, 2016). Each filter has weights plus one bias, and a layer has filters.

Example 2 Size and parameters of early layers

def conv_out(i, k, s, p):
    return (i + 2 * p - k) // s + 1

def conv_params(k, c_in, c_out):
    return k * k * c_in * c_out + c_out

print("640 px, k=3, s=1, p=1 ->", conv_out(640, 3, 1, 1))
print("640 px, k=3, s=2, p=1 ->", conv_out(640, 3, 2, 1))
print("layer 3x3, RGB -> 32 channels:", conv_params(3, 3, 32), "parameters")
print("layer 3x3, 32 -> 64 channels:", conv_params(3, 32, 64), "parameters")
full = 640 * 640 * 3 * 32
print(f"a fully connected layer from a 640x640 RGB image to 32 outputs would need {full:,} weights")
640 px, k=3, s=1, p=1 -> 640
640 px, k=3, s=2, p=1 -> 320
layer 3x3, RGB -> 32 channels: 896 parameters
layer 3x3, 32 -> 64 channels: 18496 parameters
a fully connected layer from a 640x640 RGB image to 32 outputs would need 39,321,600 weights

A convolution layer has very few parameters compared with a fully connected layer, because it reuses the same filters across the image. A stride of 2 halves the image size, so detection networks shrink their feature maps step by step to see wider context.

Removing duplicates with NMS

Detectors often predict several boxes around the same object. Greedy non-maximum suppression (NMS) keeps the highest-scoring box, removes other boxes that overlap it by more than a set IoU, and repeats until none are left. This approach was used in R-CNN (Girshick et al., 2014) and is available in libraries such as torchvision.ops.nms.

Precision, recall and AP

When matching predictions to ground truth, a prediction whose IoU with a ground-truth box exceeds 0.5 counts as correct (a true positive) under the PASCAL VOC criterion (Everingham et al., 2010). Matching proceeds in order of decreasing score, each ground-truth box can be matched only once, and duplicate predictions count as false. Cumulative precision and recall are then computed. Average precision (AP) summarises the precision–recall curve as one number. The VOC paper averages precision at 11 recall levels, while the COCO evaluation code uses 101 recall levels and averages over IoU 0.50 to 0.95, which is stricter (the dataset itself is described by Lin et al., 2014). This example computes the area under the curve at every point after making precision non-increasing as recall falls.

Example 3 NMS and then AP at IoU 0.5

One image has 4 cracks, and the detector predicts 7 boxes (simulated data).

import numpy as np

def iou(p, q):
    ix = max(0, min(p[2], q[2]) - max(p[0], q[0]))
    iy = max(0, min(p[3], q[3]) - max(p[1], q[1]))
    inter = ix * iy
    return inter / ((p[2] - p[0]) * (p[3] - p[1]) + (q[2] - q[0]) * (q[3] - q[1]) - inter)

dets = [(0.95, (100, 100, 200, 160)), (0.90, (105, 102, 203, 165)), (0.85, (300, 200, 340, 260)),
        (0.80, (500, 50, 560, 110)), (0.60, (302, 198, 345, 262)), (0.55, (700, 300, 760, 350)),
        (0.40, (900, 400, 950, 460))]
gts = [(102, 101, 201, 162), (301, 201, 342, 259), (700, 305, 758, 352), (80, 500, 140, 560)]

kept = []
for score, box in sorted(dets, reverse=True):          # greedy NMS
    if all(iou(box, k) < 0.5 for _, k in kept):
        kept.append((score, box))
print("after NMS:", [s for s, _ in kept])

used, tp = set(), []
for score, box in kept:
    g = max(range(len(gts)), key=lambda j: iou(box, gts[j]))
    hit = iou(box, gts[g]) > 0.5 and g not in used
    used.add(g) if hit else None
    tp.append(hit)
ctp = np.cumsum(tp)
prec = ctp / np.arange(1, len(tp) + 1)
rec = ctp / len(gts)
for s, p, r in zip([s for s, _ in kept], prec, rec):
    print(f"score {s:.2f}: precision {p:.2f}, recall {r:.2f}")
p_interp = np.maximum.accumulate(prec[::-1])[::-1]
ap = np.sum(np.diff(np.r_[0, rec]) * p_interp)
print(f"AP@0.5 = {ap:.3f}")
after NMS: [0.95, 0.85, 0.8, 0.55, 0.4]
score 0.95: precision 1.00, recall 0.25
score 0.85: precision 1.00, recall 0.50
score 0.80: precision 0.67, recall 0.50
score 0.55: precision 0.75, recall 0.75
score 0.40: precision 0.60, recall 0.75
AP@0.5 = 0.688

NMS removes the two duplicate boxes that overlap higher-scoring boxes. Then 3 of 5 predictions are correct and 3 of 4 cracks are found. AP is below 1 because a high-scoring false prediction sits among the correct ones and one crack is never detected.

Precision against recall from 0 to 1: a blue step curve from precision 1.0 at recall 0.25 and 0.5, falling when false predictions appear; the shaded light blue area under the curve is the AP of about 0.69
Figure 1 Precision–recall curve and AP area
A simulated image with seven predicted boxes: blue boxes are kept after NMS, grey dashed boxes are removed duplicates, and green boxes are the four real cracks
Figure 2 Boxes kept and removed by NMS

Module lab

Lab: training and evaluating a detector

  1. Compute the feature-map sizes of the first three layers of the model you will use, with Example 2
  2. Train a detector (such as a small YOLO) on the dataset from Module 3 with transfer learning
  3. Export predictions on the validation set, compute AP@0.5 with Example 3 and compare with the tool’s value
  4. Change the NMS IoU and the confidence threshold and observe precision and recall
  5. Look at the wrong predictions one by one and group the causes

Common mistakes

Watch out

  • Stacking layers without a nonlinear activation, which adds nothing over one linear layer
  • Comparing AP under different criteria, such as AP@0.5 and AP@0.5:0.95
  • Forgetting NMS and counting duplicate boxes as detections
  • Looking only at mAP without examining the wrong images
  • Training from scratch with little data instead of using transfer learning
  • Using images that are too small, so small cracks disappear after resizing

Summary

  • A neuron is a weighted sum passed through an activation; backpropagation applies the chain rule backwards from the output error to get every gradient
  • Convolution output size is , and the parameter count does not depend on image size
  • NMS keeps the highest-scoring box and removes boxes that overlap it beyond the set IoU
  • A prediction is correct when its IoU with an unmatched ground truth exceeds 0.5 (VOC criterion); AP summarises the precision–recall curve
  • Always report AP with its IoU criterion and method

Check your understanding

  1. Input 320, kernel 3, stride 2, padding 1. What is the output size?
  2. How many parameters does a 3×3 layer from 64 to 128 channels have?
  3. A sigmoid neuron outputs for an example with and input . What is under cross-entropy?
  4. Two predictions both have IoU above 0.5 with the same ground truth. How are they counted?
  5. Why is COCO AP usually lower than AP@0.5?
Answers
  1. The first is correct and the second is false
  2. It averages over IoU 0.50 to 0.95, and the higher thresholds demand much more precise boxes

Key formulas

Neuron
Convolution output size
Parameters of a convolution layer
Average precision

Key references

  1. Prince, S. J. D. (2023). Understanding deep learning. MIT Press. link
  2. Géron, A. (2022). Hands-on machine learning with Scikit-Learn, Keras, and TensorFlow (3rd ed.). O'Reilly.
  3. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep learning. MIT Press. link
  4. Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323(6088), 533-536. https://doi.org/10.1038/323533a0 link
  5. Dumoulin, V., & Visin, F. (2016). A guide to convolution arithmetic for deep learning (arXiv:1603.07285). link
  6. Girshick, R., Donahue, J., Darrell, T., & Malik, J. (2014). Rich feature hierarchies for accurate object detection and semantic segmentation. In 2014 IEEE Conference on Computer Vision and Pattern Recognition (pp. 580–587). link
  7. PyTorch Contributors. torchvision.ops.nms. Torchvision documentation. link
  8. Everingham, M., Van Gool, L., Williams, C. K. I., Winn, J., & Zisserman, A. (2010). The PASCAL visual object classes (VOC) challenge. International Journal of Computer Vision, 88(2), 303–338. link
  9. Lin, T.-Y., Maire, M., Belongie, S., Hays, J., Perona, P., Ramanan, D., Dollár, P., & Zitnick, C. L. (2014). Microsoft COCO: Common objects in context. In Computer Vision – ECCV 2014 (pp. 740–755). Springer. link
  10. COCO Consortium. Detection evaluation. Common Objects in Context. link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lecture, case discussion and in-class problem solving

Learning evidence: Quiz results and submitted exercises

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Artificial intelligence and computer vision