Images as engineering data
A digital image is an array of numbers. A greyscale image of 64 by 64 pixels holds 4096 intensities, and a colour image stores three such arrays, one per channel. Engineering images come from inspection cameras on production lines, drones over bridges and power lines, microscopes, satellites, thermal cameras and X-ray systems. Treating the pixels as 4096 unrelated inputs to a multilayer network ignores two facts: Neighbouring pixels belong together, and the same pattern, such as an edge or a crack, can appear anywhere in the image. Convolutional networks build both facts into their structure.
Formulas: Images as arrays and the cost of full connections
A greyscale image of rows and columns is an array , where counts the rows from the top and the columns from the left. A colour image has such arrays, one per channel, and so holds numbers. Cameras usually store integers from 0 to 255, which are divided by 255 to give intensities between 0 and 1.
A fully connected layer that maps all inputs to units needs a weight for every pair of input and unit:
A convolutional layer with filters of weights, each looking at all input channels, needs
parameters, whatever the size of the image, because every filter is used at every position [1, 2].
Worked example: Pixels, parameters and weight sharing
Step 1. Counting the numbers. A greyscale image of 64 by 64 pixels holds intensities, and a colour image of the same size numbers. A stored pixel value of 178 becomes the intensity .
Step 2. A dense layer. A fully connected layer from the 4096 intensities to only 8 units has
parameters.
Step 3. A convolutional layer. Eight filters of 3 by 3 weights on the single channel have
parameters. With a border of one pixel, each filter produces a feature map of 64 by 64 values, so the layer computes outputs. A fully connected layer with the same number of outputs would need
parameters, about 1.7 million times as many. Weight sharing is what makes networks for images trainable on ordinary data sets.
Convolution, feature maps and pooling
A convolutional layer slides a small filter, for example 3 by 3 weights, over the image and computes at every position the weighted sum of the pixels under it. The result is a feature map that is large where the image locally resembles the filter. A vertical-edge filter responds to vertical edges wherever they are, because the same weights are used at every position. This weight sharing drastically reduces the number of parameters compared with a fully connected layer and makes the detector equivariant to shifts [1, 2]. A layer learns many filters at once, each producing its own feature map, or channel.
Three settings shape a convolution. The kernel size sets the local window, the stride sets the step between positions, and padding adds a border so that the output can keep the input size. For an input of width W, kernel K, padding P and stride S, the output width is (W - K + 2P) / S + 1. Pooling layers then summarise small neighbourhoods, usually by their maximum, which halves the resolution and makes the representation more tolerant to small shifts. Stacking convolution, activation and pooling lets later layers see larger parts of the image: Early layers detect edges and textures, later layers combine them into parts and objects [3].
Animation: A filter slides over an image
The highlighted 3 by 3 window moves across a small concrete image with a crack. Each output value is the sum of the pixels in the window multiplied by the filter weights. Choose different filters and compare the feature maps.
Check your understanding. An input of 64 by 64 pixels passes a 5 by 5 convolution without padding and with stride 1, followed by 2 by 2 max pooling. What is the output size?
Formulas: Convolution, output size, pooling and the receptive field
A convolutional layer slides a filter of weights over the input and adds a bias [2]. Deep learning libraries such as PyTorch compute the sum without flipping the filter, which mathematicians call a cross-correlation [4]:
With the stride , the window moves pixels between neighbouring outputs. With input channels, the filter has weights for every channel, and the sum also runs over the channels. Padding adds rows and columns of zeros around the input, and the output width then is
rounded down when the division is not exact; the height follows from the same formula. An activation, usually ReLU, follows the convolution. Max pooling over windows of with stride 2 keeps the largest value of each window and halves the width and the height, and average pooling keeps the mean.
The receptive field of a unit is the size of the input window that can influence it. Starting from and a step of input pixel between neighbouring units, a layer with the window and the stride gives
so that deeper layers see larger parts of the image [3].
Worked example: A convolutional block by hand
A 4 by 4 patch of a concrete photograph contains a dark vertical crack in its third column, with intensities
| Row | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 0.9 | 0.8 | 0.2 | 0.7 |
| 1 | 0.8 | 0.8 | 0.1 | 0.8 |
| 2 | 0.9 | 0.7 | 0.1 | 0.9 |
| 3 | 0.8 | 0.9 | 0.3 | 0.6 |
The filter has the weights in each of its three rows and the bias . It compares the centre column of its window with the two neighbouring columns and responds to dark vertical lines. Because every row of the filter is the same, the sum of the nine products equals the left column sum of the window, minus twice the centre column sum, plus the right column sum.
Step 1. Output size. Without padding and with stride 1, the feature map has the width , so it has 2 by 2 values.
Step 2. The column sums. The window of output covers rows to and columns to :
| Output | Left column | Centre column | Right column |
|---|---|---|---|
| (0, 0) | |||
| (0, 1) | |||
| (1, 0) | |||
| (1, 1) |
Step 3. The four weighted sums. With the bias:
Step 4. ReLU and pooling. ReLU sets the two negative values to zero and keeps 3.4 and 3.2. Max pooling of the 2 by 2 map gives , and average pooling would give . The strong responses sit where the centre column of the window lies on the crack, at . Part A of the interactive lab applies a chosen or hand-edited filter, ReLU and max pooling to a drawn or generated image, and Part B computes every product of such a block for any input and filter.
Worked example: Sizes, parameters and receptive field of the crack network
The crack classifier of the notebook stacks three convolutions, Conv 1 to Conv 3, with 8, 16 and 32 filters of 3 by 3 weights, stride 1 and padding 1. Max pooling over 2 by 2 windows with stride 2, Pool 1 and Pool 2, follows the first two. The head averages each of the 32 last feature maps into one number and maps the 32 numbers to the two classes with a linear layer.
Step 1. Sizes and parameters.
| Layer | Width | Output | Parameters |
|---|---|---|---|
| Input | |||
| Conv 1 | |||
| Pool 1 | 0 | ||
| Conv 2 | |||
| Pool 2 | 0 | ||
| Conv 3 | |||
| Head | 32, then 2 |
Step 2. The receptive field. With the rule and :
| Layer | , | ||
|---|---|---|---|
| Input | 1 | 1 | |
| Conv 1 | 3, 1 | 1 | |
| Pool 1 | 2, 2 | ||
| Conv 2 | 3, 1 | 2 | |
| Pool 2 | 2, 2 | ||
| Conv 3 | 3, 1 | 4 |
Step 3. Reading the tables. The convolutions have parameters, and with the 66 parameters of the last layer the network has 5954. Every unit of the last feature map of 16 by 16 values sees a window of 18 by 18 pixels, about a quarter of the image width; the average pooling then combines the evidence of all positions. Part C of the lab computes such tables for other designs.
Deep architectures
LeNet showed in the 1990s that convolutional networks trained by backpropagation read handwritten digits reliably [2]. AlexNet, a deeper network trained on graphics processors with ReLU activations and dropout, won the 2012 ImageNet challenge by a wide margin [5, 6]. VGG networks used only small 3 by 3 filters stacked deeply [7]. Residual networks added shortcut connections that let a layer learn a correction to its input, which made networks with more than a hundred layers trainable [8]. Vision transformers split an image into patches and process them with the attention mechanism of Week 13; with enough data they match or exceed convolutional networks [9].
Formulas: Stacked small filters, residual connections and patches
A stack of convolutions of 3 by 3 with stride 1 has the receptive field , by the rule of the previous section. With channels in and out, it needs weights, while a single convolution with the same receptive field needs . For , this is against , and the stack adds two more nonlinearities, which is why VGG networks are built from 3 by 3 filters [7].
A residual block adds its input to the output of a few layers, so that the layers learn a correction rather than a whole new representation [8]:
By the chain rule, the derivative of the loss passes the block as
The added 1 lets gradients reach early layers even when is small, which made networks with more than a hundred layers trainable.
A vision transformer cuts an image of pixels with channels into square patches of pixels, flattens each patch into a vector and projects it linearly [9]:
Worked example: Small filters, shortcuts and patches
Step 1. Three small filters or one large filter. With 64 channels in and out, one 3 by 3 convolution has parameters, and three of them have . Their receptive field grows as , and . A single 7 by 7 convolution with the same receptive field has parameters, so the stack needs only of them.
Step 2. A residual block. A block computes with the small weights and . For the input :
Since the ReLU is active, its slope is 1, and the derivatives are
Step 3. Twenty blocks. The gradient that passes 20 such blocks is multiplied by the product of their derivatives. Without shortcuts it shrinks to and vanishes; with shortcuts it is , so the early layers still learn.
Step 4. Patches. An image of 224 by 224 pixels in three colours, cut into patches of 16 by 16 pixels, gives
so the transformer processes 196 vectors of 768 numbers, plus one extra vector whose output serves for the classification. Week 13 explains how attention combines them.
Training with little data
Engineering datasets are small compared with ImageNet: a few hundred labelled crack photographs, a few thousand defect images. Two techniques make deep networks usable nonetheless. Data augmentation creates plausible variants of the training images by flipping, rotating, cropping or changing brightness, which teaches invariances that the task requires. Transfer learning starts from a network pretrained on a large dataset and retrains only its last layers or fine-tunes all of them with a small learning rate; Yosinski and colleagues showed that early layers learn general features that transfer well between tasks [10]. Cha and colleagues trained a convolutional network on patches of concrete photographs to detect cracks under varied lighting [11], and similar studies inspect steel strip surfaces [12], crops and weeds [13] and traffic signs [14].
Check your understanding. A team has 400 labelled images of weld defects. Which approach is most promising?
Formulas: Augmentation, transfer learning and the softmax head
Augmentations are operations on the pixel grid that keep the label. For a square image of pixels with rows and columns counted from 0, a mirror image and a rotation by 90 degrees anticlockwise take their values from
The four rotations by multiples of 90 degrees, with and without mirroring, give eight versions of every image. A change of contrast and brightness maps every intensity to , where clip keeps the result between 0 and 1.
Transfer learning keeps the layers of a network pretrained on a large data set, which compute a feature vector of length , and adds a new final layer for the classes of the task [10]. The new layer computes a score per class and the softmax function turns the scores into probabilities:
Training minimises the cross-entropy of the true class , whose gradients are
where is 1 for the true class and 0 otherwise. The new layer has parameters. When the pretrained layers are frozen, only these are trained, which suits data sets of a few hundred images.
Worked example: Eight versions of one image
Step 1. Mirror and rotation. A 3 by 3 image with a diagonal crack, , is mirrored and rotated by the formulas above:
| Row | Original | Mirrored | Rotated by 90 degrees |
|---|---|---|---|
| 0 | 0.1, 0.7, 0.8 | 0.8, 0.7, 0.1 | 0.8, 0.8, 0.3 |
| 1 | 0.7, 0.2, 0.8 | 0.8, 0.2, 0.7 | 0.7, 0.2, 0.8 |
| 2 | 0.8, 0.8, 0.3 | 0.3, 0.8, 0.8 | 0.1, 0.7, 0.8 |
For example, the mirrored value in row 0 and column 0 is , and the rotated value in row 2 and column 0 is . The crack runs from the top left to the bottom right in the original and from the top right to the bottom left in both new images, which are still valid examples of a crack.
Step 2. Contrast and brightness. With and , the crack pixels become , and , and the background pixels and , which clip sets to 1. The notebook draws a random mirror and a random number of quarter turns for every batch, so that each of the eight versions appears with the probability . Part D of the interactive lab produces the eight versions of any small image and follows a pixel through them.
Worked example: A new head on a frozen network
Step 1. Parameters. ResNet-18 has 11,689,512 parameters, of which its final layer for the 1000 ImageNet classes has [6, 8]. A crack detector replaces this layer by one for two classes, with parameters, so the network has parameters. With the other layers frozen, only 1026 of them, 0.0092%, are trained on a set of 600 crack images.
Step 2. Softmax. For one image, the new layer gives the scores for no crack and for crack:
Step 3. Loss and gradients. The image shows a crack, , so . The gradients of the scores are and : Training raises the crack score and lowers the other. A feature with the value gives its weight to the crack score the gradient . Part E of the interactive lab computes and applies these gradients for a small head.
Beyond classification
Classification assigns one label to an image. Object detection finds and labels every object with a bounding box; YOLO treats detection as a single regression problem and runs in real time [15]. Semantic segmentation labels every pixel; U-Net combines a contracting path with an expanding path and skip connections and became a standard for segmentation with few training images [16]. For a bridge inspector, a classifier says "crack present", a detector draws a box around each crack, and a segmentation network outlines the crack so that its length and width can be measured.

Formulas: Boxes, overlap, suppression and masks
A detector describes an object by a box with the corners at the top left and at the bottom right, in pixels. The overlap of a predicted box with a true box is measured by the intersection over union:
where the denominator is the area of the union. A detection usually counts as correct when its IoU with a true box reaches a threshold such as 0.5. Detectors propose many overlapping boxes, and non-maximum suppression cleans them up: It keeps the box with the highest confidence, removes every other box whose IoU with it exceeds a threshold, and repeats with the remaining boxes. YOLO divides the image into cells, and each cell predicts boxes, each with four coordinates and a confidence, together with class probabilities, so that one pass of the network outputs numbers [15].
A segmentation network such as U-Net labels every pixel [16]. Comparing a predicted mask with the true mask pixel by pixel gives the true positives TP, the false positives FP and the false negatives FN, and two overlap measures:
With a known size of a pixel on the surface, a mask of pixels covers the area , and the mean width of a crack is its area divided by its length.
Worked example: Overlap of boxes and suppression
Step 1. IoU with the true box. An inspector marked a crack with the box . The detector proposes with the confidence 0.9:
The areas are for the intersection, for and for :
which exceeds 0.5, so the detection counts as correct.
Step 2. Suppression. The detector also proposes with the confidence 0.7. Its overlap with has , and the area , and has the area :
With a suppression threshold of 0.5, is kept as the more confident box and is removed, so the crack is reported once. The removal also matters for the score: alone would have the IoU 0.489905 with the true box and would count as a miss.
Step 3. Size of a YOLO output. With , and the classes of the original paper, the network outputs numbers per image.
Worked example: Measuring a crack from a mask
A segmentation network labels a patch of 6 by 6 pixels, each 0.5 mm wide on the concrete surface. Comparing its mask with the true mask gives, row by row:
| Row | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| 1 | TP | |||||
| 2 | TP | FP | ||||
| 3 | FN | TP | ||||
| 4 | TP | |||||
| 5 | TP | FP | ||||
| 6 | TP |
Step 1. Counts. The table has TP = 6, FP = 2 and FN = 1, and the remaining pixels are true negatives.
Step 2. Overlap measures.
which agrees with . The pixel accuracy looks excellent only because most pixels are background, which is why segmentation is judged by IoU or Dice.
Step 3. Width of the crack. Each pixel covers . The predicted crack has pixels and the area ; the true crack has pixels and . Both run through all six rows, a length of , so the mean width is according to the network and in truth. Part F of the interactive lab computes boxes, suppression and masks for any input.
Seeing what the network sees
High accuracy does not prove that a network uses the right evidence. A defect classifier may learn the lighting of the station where defective parts were photographed, or the ruler that appears only in images of damaged specimens. Grad-CAM weighs the feature maps of the last convolutional layer by the gradient of the class score and produces a coarse heatmap of the regions that drove the decision [17]. Checking such maps on a sample of test images, and testing the network on images from new cameras and sites, belongs to every engineering deployment. Vision models are also vulnerable to small, deliberate perturbations of the input that change their decisions, which matters wherever an attacker could manipulate the images [18].
Check your understanding. A crack classifier reaches 99 percent test accuracy, but Grad-CAM shows that it attends to a timestamp printed in the corner of the images. What should be concluded?
Formulas: Grad-CAM and the sensitivity to small perturbations
Grad-CAM explains the score of a class with the feature maps of the last convolutional layer, each of positions [17]. The weight of a map is the mean gradient of the class score over the map, and the heatmap is the weighted sum of the maps, of which ReLU keeps the positive part:
The map has the coarse resolution of the last feature maps. It is enlarged to the size of the image and divided by its maximum for display, as in the notebook.
Small changes of many pixels can add up. For a linear score over pixels, a change of at most per pixel changes the score by at most
and the bound is reached by , which lowers the score as far as possible. The bound grows with the number of pixels, which is one reason why image classifiers can be fooled by changes too small to see [18].
Worked example: Grad-CAM on two feature maps
The last layer of a crack classifier has two feature maps of 3 by 3 values. responds to the crack in the centre column and to the texture on the left:
| Row | ||||
|---|---|---|---|---|
| 0 | 0, 1.2, 0.8 | 0.2, 0.4, 0.3 | 0.9, 0.2, 0 | −0.1, 0, −0.2 |
| 1 | 0.1, 1.5, 0.9 | 0.3, 0.5, 0.3 | 0.8, 0.1, 0 | −0.1, −0.1, 0 |
| 2 | 0, 1.1, 0.7 | 0.2, 0.4, 0.1 | 1, 0.3, 0.1 | −0.2, 0, −0.2 |
Step 1. Weights of the maps. The gradients of the first map add up to 2.7 and those of the second to −0.9, so
Step 2. Weighted sum, ReLU and normalisation. The weighted sums, their positive parts and the division by the largest value, 0.44, give
| Position | ReLU | Divided by 0.44 | |
|---|---|---|---|
| (0, 0) | 0 | 0 | |
| (0, 1) | 0.34 | 0.772727 | |
| (0, 2) | 0.24 | 0.545455 | |
| (1, 0) | 0 | 0 | |
| (1, 1) | 0.44 | 1 | |
| (1, 2) | 0.27 | 0.613636 | |
| (2, 0) | 0 | 0 | |
| (2, 1) | 0.3 | 0.681818 | |
| (2, 2) | 0.2 | 0.454545 |
The heatmap lights up the centre column, the crack, and ignores the left column, whose map has a negative weight. If it instead lit up a timestamp or a ruler, the classifier would be right for the wrong reason. Part G of the interactive lab computes the heatmap for any maps and gradients.
Worked example: A perturbation too small to see
A linear crack detector scores images of 64 by 64 pixels, , with weights of size , and reports a crack when . A crack image has the score . A change of every intensity by two grey levels, , against the sign of its weight lowers the score by
to , and the crack is no longer reported. No pixel has changed visibly, yet the decision has flipped; a change of per pixel, less than two grey levels, already suffices. Part H of the lab shows such a perturbation on a small image.
Python step 11: Images, batches and network classes
The Python step of this week is part of the Colab notebook, where every explanation stands next to a cell that runs it and the step closes with a quick check and exercises with immediate feedback. The printable lecture notes contain the same step together with the outputs of its code. The Colab button below opens the notebook at the step. Run the setup cell just above the step first, since the exercises use its check function.
Review cards
Select a card to turn it over.
Continue the week
The week continues with the simulation and the self-assessment of the interactive lab and with the Python step and the hands-on work of the Colab notebook. The week overview lists the discipline challenges, the weekly task and the research assignment.
Interactive lab Colab notebook Self-assessment Week overview and tasks
References
[1] LeCun, Y., Boser, B., Denker, J. S., et al. (1989). Backpropagation applied to handwritten zip code recognition. Neural Computation, 1(4), 541-551. https://doi.org/10.1162/neco.1989.1.4.541
[2] LeCun, Y., Bottou, L., Bengio, Y., & Haffner, P. (1998). Gradient-based learning applied to document recognition. Proceedings of the IEEE, 86(11), 2278-2324. https://doi.org/10.1109/5.726791
[3] LeCun, Y., Bengio, Y., & Hinton, G. (2015). Deep learning. Nature, 521(7553), 436-444. https://doi.org/10.1038/nature14539
[4] Paszke, A., Gross, S., Massa, F., et al. (2019). PyTorch: An imperative style, high-performance deep learning library. In Advances in Neural Information Processing Systems 32 (pp. 8024-8035). https://arxiv.org/abs/1912.01703
[5] Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2017). ImageNet classification with deep convolutional neural networks. Communications of the ACM, 60(6), 84-90. https://doi.org/10.1145/3065386
[6] Deng, J., Dong, W., Socher, R., Li, L.-J., Li, K., & Fei-Fei, L. (2009). ImageNet: A large-scale hierarchical image database. In 2009 IEEE Conference on Computer Vision and Pattern Recognition (pp. 248-255). https://doi.org/10.1109/CVPR.2009.5206848
[7] Simonyan, K., & Zisserman, A. (2015). Very deep convolutional networks for large-scale image recognition. In 3rd International Conference on Learning Representations (ICLR 2015). https://arxiv.org/abs/1409.1556
[8] He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep residual learning for image recognition. In 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR) (pp. 770-778). https://doi.org/10.1109/CVPR.2016.90
[9] Dosovitskiy, A., Beyer, L., Kolesnikov, A., et al. (2021). An image is worth 16x16 words: Transformers for image recognition at scale. In 9th International Conference on Learning Representations (ICLR 2021). https://arxiv.org/abs/2010.11929
[10] Yosinski, J., Clune, J., Bengio, Y., & Lipson, H. (2014). How transferable are features in deep neural networks?. In Advances in Neural Information Processing Systems 27 (pp. 3320-3328). https://arxiv.org/abs/1411.1792
[11] Cha, Y.-J., Choi, W., & Büyüköztürk, O. (2017). Deep learning-based crack damage detection using convolutional neural networks. Computer-Aided Civil and Infrastructure Engineering, 32(5), 361-378. https://doi.org/10.1111/mice.12263
[12] Song, K., & Yan, Y. (2013). A noise robust method based on completed local binary patterns for hot-rolled steel strip surface defects. Applied Surface Science, 285, 858-864. https://doi.org/10.1016/j.apsusc.2013.09.002
[13] Kamilaris, A., & Prenafeta-Boldú, F. X. (2018). Deep learning in agriculture: A survey. Computers and Electronics in Agriculture, 147, 70-90. https://doi.org/10.1016/j.compag.2018.02.016
[14] Stallkamp, J., Schlipsing, M., Salmen, J., & Igel, C. (2012). Man vs. computer: Benchmarking machine learning algorithms for traffic sign recognition. Neural Networks, 32, 323-332. https://doi.org/10.1016/j.neunet.2012.02.016
[15] Redmon, J., Divvala, S., Girshick, R., & Farhadi, A. (2016). You only look once: Unified, real-time object detection. In 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR) (pp. 779-788). https://doi.org/10.1109/CVPR.2016.91
[16] Ronneberger, O., Fischer, P., & Brox, T. (2015). U-Net: Convolutional networks for biomedical image segmentation. In Medical Image Computing and Computer-Assisted Intervention (MICCAI 2015), LNCS 9351 (pp. 234-241). Springer. https://doi.org/10.1007/978-3-319-24574-4_28
[17] Selvaraju, R. R., Cogswell, M., Das, A., Vedantam, R., Parikh, D., & Batra, D. (2017). Grad-CAM: Visual explanations from deep networks via gradient-based localization. In 2017 IEEE International Conference on Computer Vision (ICCV) (pp. 618-626). https://doi.org/10.1109/ICCV.2017.74
[18] Kose, U. (2019). Techniques for adversarial examples threatening the safety of artificial intelligence based systems. In I. International Science and Innovation Congress (INSI Congress 2019). Pamukkale, Denizli, Türkiye. https://arxiv.org/abs/1910.06907