Zero Labs
Industry News / AI

Convolutional Neural Networks Explained: How AI Understands Images

Source · Towards AI By Sanika Tare

From the publisher’s feed, collected in the ZeroLabs newsroom.

How a network goes from a grid of raw numbers to “that’s a cat”.IntroductionSo far in this series we’ve worked with networks that take in a handful of numbers and produce a prediction. Images break that comfortable picture. A single photo contains tens of thousands of numbers, and they aren’t independent. Pixels next to each other belong together, and what matters is often where things are relative to each other, not the raw values.An ordinary neural network ignores all of that. It treats an image as one long, flat list. Convolutional Neural Networks (CNNs) were designed to respect the structure of images, and they’re behind much of what computer vision does today:• Image classification• Face recognition• Object detection• Medical image analysis• Self-driving systemsHow does a computer see an image?A computer doesn’t see a cat. It sees numbers. An image is a grid of tiny squares called pixels, and each pixel holds a value for its intensity.A grayscale image has one number per pixel. A colour image has three.0 20 5080 120 200255 180 90The grid’s size gives the image dimensions, such as 28 × 28. In grayscale, 0 means black and 255 means white. Colour images use three RGB channels, one grid each for red, green and blue, stacked together. So a colour image is height × width × 3.Why not just use a normal neural network?Take a small colour image of 100 × 100 pixels:100 × 100 × 3 = 30,000 input valuesIf the first fully connected layer has just 1,000 neurons, that layer alone needs 30,000 × 1,000 = 30 million weights. And that’s for a tiny image. The problems stack up quickly:• Huge number of parameters, which also invites overfitting (see Article #5).• Expensive computation.• Spatial relationships are lost. Flattening the image throws away the fact that two pixels were neighbours.• Poor scalability. Doubling the image size multiplies the cost again.What is a CNN?A CNN is a neural network designed to automatically learn useful features from images.Instead of connecting every pixel to every neuron, a CNN scans the image with small filters that look at one local patch at a time. The basic pipeline looks like this:The basic building blocks of a CNN.What is convolution?This is the heart of the whole article, so let’s slow down.A filter (or kernel) is a small grid of numbers. We place it over a patch of the image, multiply each filter value by the pixel underneath it (element-wise multiplication), and add everything up. That single number goes into the output. Then we slide the filter across the image, one step at a time, and repeat. The grid of results is called a feature map.A 2×2 filter sliding over a 3×3 image produces a 2×2 feature map.Try the first step by hand: 1×1 + 2×0 + 4×0 + 5×1 = 6. Each output number answers one question: how strongly does this little patch match the pattern the filter is looking for?How does a filter detect features?Different filters respond to different patterns. A classic hand-made example is a vertical-edge filter:1 0 -11 0 -11 0 -1Where the left side of a patch is bright and the right side is dark, this filter produces a large value. Where the patch is flat, it produces about zero. Other filters light up on horizontal edges, corners or textures.The magic happens when you stack layers. Early layers detect simple things, and later layers combine them into something richer:Deeper layers learn increasingly complex features.Layer 1 → edgesLayer 2 → shapesLayer 3 → parts (an eye, a wheel)Layer 4 → objects (a face, a car)Kernel and filter• A kernel is a small grid of weights used to extract features from an image. People often use “filter” and “kernel” interchangeably.• Common kernel sizes are 3×3 and 5×5.• The values inside a kernel are learnable parameters, just like weights in a normal network.• A convolutional layer uses many filters, and each one learns to detect a different feature.Here is the big parameter win. A 3×3 filter on an RGB image has 3×3×3 = 27 weights plus a bias. The same filter is reused across the entire image, which is called parameter sharing. A layer with 32 such filters needs only 896 parameters, compared with millions for a dense layer.StrideStride determines how many pixels the filter moves at each step.Stride = 1 → moves one pixel at a timeStride = 2 → moves two pixels at a timeA larger stride skips positions, so the output gets smaller. Without padding, the output size is (i − k) / s + 1, where i is the input size, k the kernel size and s the stride (rounded down). For a 7-pixel-wide input and a 3×3 kernel:PaddingEvery time we convolve, the image shrinks. Also, pixels at the border get covered by the filter fewer times than pixels in the middle, so edge information gets underused. Padding fixes both by adding extra pixels (usually zeros) around the image.Zeros around the border keep the output the same size as the input.• Valid padding: no padding. The output shrinks.• Same padding: padding is added so the spatial dimensions stay the same.With padding p, the output size becomes (i − k + 2p) / s + 1.Activation: ReLUJust as in Article #2, a CNN needs non-linearity. Without it, stacking layers would collapse into one big linear operation. After each convolution, the feature map goes through an activation, most commonly ReLU:ReLU(x) = max(0, x)-5 → 02 → 28 → 8Negative values become zero and positive values pass through untouched. ReLU adds non-linearity so the network can learn complex patterns, and it’s computationally very cheap. (Leaky ReLU is a variant that avoids “dead neurons” by letting a small negative slope through.)Feature mapsThe output produced after applying a filter is called a feature map.One filter gives one feature map, which shows where in the image that feature appears. A layer with 32 filters gives 32 feature maps, stacked like channels, and those become the input for the next layer.PoolingFeature maps are big, and we don’t need to keep every location exactly. Pooling shrinks them while keeping the most important information.Pooling summarizes each small block with a single number.• Max pooling keeps the largest value in each block. For [1 3; 2 5], the result is 5.• Average pooling keeps the mean of each block.Why bother? Pooling reduces dimensions and computation, keeps the strongest signals, and adds some robustness to small shifts. If a feature moves by a pixel, the pooled output barely changes. It also helps reduce overfitting.The complete CNN architectureA typical CNN for image classificationConvolution, ReLU and pooling are often repeated several times. Early in the network the images are large and the features simple. By the end, the maps are small and the features are rich. Then the flattened result goes through fully connected layers, and a softmax turns the final scores into probabilities.What does flattening mean?Flattening unrolls feature maps into one long listFully connected layers expect a one-dimensional list of numbers, not a grid. Flattening simply unrolls all the feature maps into one long vector, so the classifier at the end can work with it.How does a CNN learn?The filters are just weights, so backprop and gradient descent update them.CNN filters are not manually programmed. The network learns them during training.At the start, the filters hold random numbers and detect nothing useful. As training goes on, gradient descent adjusts them so they respond to patterns that help reduce the loss. Edge detectors emerge on their own, not because anyone designed them, but because they’re useful.A simple classification exampleThe softmax output is a probability for each class.A photo goes in. The convolutional layers extract features, the fully connected layers weigh the evidence, and softmax converts the final scores into probabilities that add up to 1. Here the network is 92% sure it’s a cat, so it predicts “cat”.CNNs in real life• Face recognition on phones• Number plate recognition• X-ray and scan analysis• Object detection in cameras and vehicles• Image searchHandwriting recognitionSee it in PythonA small CNN for MNIST handwritten digits in Keras. The workflow is: load, normalize, build, train, evaluate, predict.import tensorflow as tffrom tensorflow.keras import layers, models# 1) Load and normalize(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()x_train = x_train[…, None] / 255.0 # (60000, 28, 28, 1)x_test = x_test[…, None] / 255.0# 2) Build the CNNmodel = models.Sequential([layers.Input(shape=(28, 28, 1)),layers.Conv2D(32, 3, activation=”relu”), # 28x28 -> 26x26x32layers.MaxPooling2D(2), # -> 13x13x32layers.Conv2D(64, 3, activation=”relu”), # -> 11x11x64layers.MaxPooling2D(2), # -> 5x5x64layers.Flatten(), # -> 1600layers.Dense(64, activation=”relu”),layers.Dense(10, activation=”softmax”), # 10 digit classes])# 3) Trainmodel.compile(optimizer=”adam”,loss=”sparse_categorical_crossentropy”,metrics=[“accuracy”])model.fit(x_train, y_train, epochs=5, validation_split=0.1)# 4) Evaluate and predictprint(model.evaluate(x_test, y_test))probs = model.predict(x_test[:1])print(“Predicted digit:”, probs.argmax())The comments show the size at each step. Each 3×3 convolution trims 2 pixels, and each pooling halves the size. The whole network has about 122,000 parameters, which is tiny compared with a dense network on raw pixels. A model like this typically reaches roughly 98 to 99% accuracy on MNIST after a few epochs.Common beginner questionsWhat is a convolution? Sliding a small filter over an image, multiplying and summing at each position, to produce a feature map.What is a kernel, and what is a filter? A kernel is the small grid of learnable weights. A filter is the same idea (some people use “filter” for the full set of kernels across channels).Why do we need pooling? To shrink feature maps, cut computation, and make features tolerant to small shifts.What is stride? What is padding? Stride is how far the filter moves per step. Padding adds a border so the output doesn’t shrink and edges aren’t under-used.How does a CNN recognize edges? Some filters end up with values that respond strongly to sudden brightness changes, like the vertical-edge filter above. The network learns these on its own.Does a CNN already know what a cat looks like? No. It starts with random filters and learns cat-relevant features from labelled examples.How are filters learned? Through backpropagation and gradient descent, exactly like any other weights.CNN vs ANN? An ANN connects every input to every neuron. A CNN uses small shared filters that scan the image, so it needs far fewer parameters and keeps spatial structure.ConclusionHow a CNN builds understanding, step by step.A CNN learns to transform raw pixels into increasingly meaningful visual features.CNNs are brilliant at spatial patterns like images. But what happens when the order of information matters, like words in a sentence, stock prices over time, or a sequence of events? An image can be read in any order. A sentence can’t.Convolutional Neural Networks Explained: How AI Understands Images was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.