1. Home
  2. Explore
  3. Computer Science
  4. Convolutional Neural Networks

Study methods

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

Convolutional Neural Networks

How Convolutional Neural Networks Make Sense of Images

A standard fully connected neural network can, in principle, classify an image. But images have special structure: nearby pixels form local patterns, and the same pattern can appear in many places. A convolutional neural network, or CNN, is designed to take advantage of those properties.

Understanding CNNs is therefore about more than learning a new layer type. It is about seeing how assumptions about a problem shape a network’s architecture—and how a suitable architecture can produce strong results with fewer parameters.

From an image to a classification

Suppose a system must decide what appears in an image. Its input is the image, and its output is a choice among possible categories, such as cat, bird, or car.

For classification, each category can be represented by a position in a one-hot vector. If the correct category is cat, the cat position contains 111 and all other positions contain 000. The vector’s length equals the number of categories the system can represent. A system designed for thousands of object types needs an output vector with thousands of entries.

The network typically produces scores that are converted by a softmax operation into a probability distribution, denoted here by y′\mathbf{y}'y′. Training compares that output with the correct one-hot target, y^\hat{\mathbf{y}}y^​, using cross-entropy. The training goal is to make the cross-entropy small, which means assigning high probability to the correct category.

A common simplifying assumption is that every input image has the same dimensions. Real images vary in size and shape, so they are often resized, or rescaled, before being passed into the network. For example, a system might always receive images with a resolution of 100×100100 \times 100100×100 pixels.

An image as data

A computer represents a color image as a three-dimensional tensor—a general term for an array with more than two dimensions. The three dimensions correspond to:

  • Height: the number of pixel rows.
  • Width: the number of pixel columns.
  • Channels: the values recorded for each pixel.

A color image commonly has three channels, corresponding to red, green, and blue. Each pixel therefore has three values describing the intensity of those colors. A grayscale image has one channel.

An image of size 100×100100 \times 100100×100 with three color channels contains 100×100×3100 \times 100 \times 3100×100×3 numbers. One way to feed this image into a traditional fully connected network is to flatten the tensor: take all its values and arrange them in a single long vector. Each entry in that vector records the intensity of one color channel at one pixel location.

Why a fully connected network becomes expensive

In a fully connected layer, every neuron has a separate weight for every input value. If a flattened image has 100×100×3100 \times 100 \times 3100×100×3 values and the first layer has 1,0001{,}0001,000 neurons, that layer needs

1,000×100×100×3=3×1071{,}000 \times 100 \times 100 \times 3 = 3 \times 10^71,000×100×100×3=3×107

weights, before counting biases.

A large number of parameters gives a model more flexibility: it can represent more possible relationships between inputs and outputs. But flexibility comes with a risk. A highly flexible model can fit accidental details in its training examples instead of learning patterns that generalize well. This is called overfitting.

CNNs address the problem by building in assumptions about images. Those assumptions restrict what the network can learn in particular ways, while making it easier to learn useful visual patterns.

A fully connected image model treats every pixel value as potentially connected to every neuron. A CNN encodes the idea that useful image patterns are usually local and may occur in different places.

Think About It: If a small patch of pixels is enough to reveal a bird’s eye, why might a neuron not need information from the entire image?

Local patterns and receptive fields

Image recognition often depends on detecting meaningful patterns. A system may recognize a bird by finding features such as a beak, an eye, or a claw, and then combining evidence from those features. People also often identify objects by noticing a few distinctive visual cues.

A small local patch can be enough to detect one of these cues. A neuron looking for an eye, for example, may need information from only a small region rather than every pixel in the image.

A CNN captures this idea with a receptive field: the region of the input image that a particular neuron examines. Instead of connecting that neuron to every pixel, the network connects it only to values inside its receptive field. The neuron combines those values using weights, adds a bias, and passes the result through an activation function.

For a receptive field covering a 3×33 \times 33×3 area of a color image, the input contains 3×3×3=273 \times 3 \times 3 = 273×3×3=27 values. The neuron has one weight for each of those values, plus a bias. It can use those weights to respond to a particular arrangement of colors and intensities in that local patch.

Receptive fields can overlap. That is useful because a pattern may lie across the boundary between two neighboring patches. Overlap helps ensure that patterns in different parts of an image are not missed.

A region can also have several neurons assigned to it. Different neurons can learn to detect different patterns in the same area—for example, one might respond to a diagonal edge, while another responds to a small texture. Receptive fields can be made larger or smaller, rectangular rather than square, or designed to include selected channels. The choice depends on the task and on what kinds of patterns are expected.

Kernel size and stride

In a common image-processing setup, a receptive field includes all the input channels. Its spatial dimensions—its height and width—are called the kernel size. For example, a kernel size of 3×33 \times 33×3 means that each filter examines a patch three pixels high and three pixels wide, across all channels.

Kernel sizes of 3×33 \times 33×3 are common. Larger sizes, such as 7×77 \times 77×7 or 9×99 \times 99×9, are also possible, but are less common in the basic arrangement described here. A single region is often monitored by a group of neurons, rather than just one; for instance, there might be 646464 or 128128128 neurons assigned to each location.

To examine the whole image, the receptive field moves across it. The number of pixels it moves at each step is the stride. A stride of 111 moves one pixel at a time; a stride of 222 moves two pixels at a time. Stride is a design choice, and small values help neighboring receptive fields overlap.

At the image boundary, a receptive field may extend outside the available pixels. One common solution is padding: adding values around the image so that the receptive field can still be placed near the edge. Zero padding fills those added positions with zeros. Other padding strategies can use values such as the image average or values copied from the boundary.

Think About It: Why can overlapping receptive fields make a detector less likely to miss a pattern near the border between two patches?

Parameter sharing: one detector, many locations

A local pattern can occur in different parts of an image. A beak could appear near the upper-left corner or near the center. If the network needs to recognize the same kind of beak wherever it appears, it could learn a separate detector for every location. But that would repeat the same work and require more parameters.

CNNs reduce this repetition through parameter sharing. Neurons that examine different image regions can use the same weights. In effect, the network learns one detector and applies it at many locations.

Shared weights do not imply identical outputs. Two neurons can use the same weights but receive different input patches. One might examine a patch containing a beak, while another examines a patch containing sky. Because their inputs differ, their outputs can differ even though their parameters are identical.

The shared weights for one detector are called a filter. A network can have many filters, each with its own parameters. One filter might respond strongly to a particular edge or texture; another might respond to a different pattern. At each image location, the same set of filters is applied to the local patch.

Parameter sharing is meaningful when different locations are expected to contain the same kinds of patterns. It would usually be redundant for two neurons examining the exact same region to share all their weights, since they would receive the same input and produce the same output. The useful arrangement is to apply shared filters to different locations.

Why these choices define a convolutional layer

A convolutional layer combines two ideas:

  1. Each neuron examines only a local receptive field.
  2. The same filter parameters are reused across different spatial locations.

These choices reduce the network’s flexibility compared with a fully connected layer. In a fully connected layer, every neuron could learn a different connection to every input value. A convolutional layer restricts each neuron to a local region and requires corresponding neurons at different locations to share parameters.

Those restrictions are often a strength for image tasks. They encode a useful assumption: important patterns tend to be local, and the same pattern may appear in different parts of the image. This is an example of inductive bias—an architectural preference for certain kinds of solutions. A stronger bias is not automatically a disadvantage. A highly flexible model can overfit, while a more restricted model can perform well when its restrictions match the task.

Think About It: If a pattern detector can be reused across the entire image, what information would be lost by learning a separate copy of that detector for every location?

Filters, convolution, and feature maps

The same CNN can be described from a filter-based viewpoint. A convolutional layer contains a collection of filters. For a color image, a filter with spatial size 3×33 \times 33×3 has depth 333, one value for each of the red, green, and blue channels at each spatial position. Its full size is therefore 3×3×33 \times 3 \times 33×3×3.

A filter is applied by placing it over a local image region and combining its values with the image values, usually through element-by-element multiplication followed by summation. This is an inner product. The filter is then moved across the image according to the stride, and the calculation is repeated at each position.

The result at each location indicates how strongly the local image patch matches the pattern represented by that filter. A filter that responds strongly to a particular arrangement of values can be understood as detecting that pattern.

Each filter produces a two-dimensional grid of results. That grid is called a feature map. If a convolutional layer has 646464 filters, it produces 646464 feature maps—one for each filter. Together, those maps can be viewed as a new image-like representation with 646464 channels. Each channel records where one learned pattern was detected and how strongly it responded.

For example, placing a 3×33 \times 33×3 filter over a 6×66 \times 66×6 image with stride 111 and no padding produces a 4×44 \times 44×4 map: there are four horizontal placements and four vertical placements. Padding changes which positions can be covered at the edges.

A filter’s values are model parameters learned during training; they are not usually known in advance. A filter may also have a bias. The values of the filter and its bias are adjusted so that the network’s outputs improve on the training task.

Stacking convolutional layers

The output of one convolutional layer can be passed to another. If the first layer has 646464 filters, its output has 646464 channels. A filter in the next layer must therefore span those 646464 input channels. If that second layer uses a spatial kernel size of 3×33 \times 33×3, each filter has a size of 3×3×643 \times 3 \times 643×3×64.

A small kernel does not mean the network can only represent small-scale patterns. As layers are stacked, each location in a later feature map depends on a larger region of the original image. For example, a 3×33 \times 33×3 region in the first layer’s output can draw on a 5×55 \times 55×5 region of the original image. Deeper layers can therefore combine local detections into larger patterns.

This is one reason deep CNNs can recognize complex objects while using relatively small kernels: early layers detect local features, and later layers build on them to represent patterns spanning larger regions.

Pooling and reducing spatial size

Another operation often used with convolutional layers is pooling. Pooling takes groups of nearby values and replaces each group with a representative value. Unlike a learned filter, a pooling operation has no weights to train. Its behavior is fixed, so it is a parameter-free operation.

In max pooling, the largest value in each group is selected. For instance, a 2×22 \times 22×2 region is reduced to its maximum value. Other pooling rules are possible: min pooling selects the smallest value, while average pooling selects the mean.

Pooling reduces the spatial dimensions of the feature maps while retaining the number of channels. If a feature map is 4×44 \times 44×4 and non-overlapping 2×22 \times 22×2 groups are used, the pooled map becomes 2×22 \times 22×2. A layer with 646464 channels still has 646464 channels after this operation, but each channel is spatially smaller.

This reduction can lower the amount of computation in later layers. It can also make the representation less sensitive to small spatial differences, but it may discard useful detail. If the task depends on very fine distinctions, reducing the feature maps may harm performance.

A common design alternates groups of convolutional layers with pooling. However, pooling is not mandatory. Some networks use convolutional layers throughout and omit pooling, especially when computational resources are sufficient and preserving spatial information is important.

Think About It: What is the tradeoff when a feature map is made smaller: which practical benefit is gained, and what kind of information might be lost?

Turning feature maps into a classification

After several convolutional and possibly pooling operations, a network still needs to produce a final classification. One traditional approach is to flatten the output feature maps: arrange all their values into one long vector. That vector is then passed into one or more fully connected layers, followed by a final output such as a softmax distribution over classes.

A basic image-classification network may therefore follow this sequence:

  1. Convolutional layers detect and combine image patterns.
  2. Pooling operations may reduce the feature maps’ spatial size.
  3. Flattening converts the final feature maps into a vector.
  4. Fully connected layers use that vector to make a decision.
  5. A softmax produces class probabilities.

The convolutional stages exploit local image structure, while the final fully connected stages combine the resulting features to make a whole-image prediction.

CNNs and the game of Go

CNNs are also useful beyond ordinary image classification when another task has similar structure. The game of Go offers an example. A network can receive the current board position and classify possible next moves. On a 19×1919 \times 1919×19 board, there are 19×1919 \times 1919×19 possible positions for a move, so the output can assign a score or probability to each location.

A simple representation uses one value for each board location: 111 for a black stone, −1-1−1 for a white stone, and 000 for an empty position. This forms a 19×1919 \times 1919×19 array, which can be treated like a small image. More elaborate representations can use multiple values, or channels, to describe each position. One described Go representation uses 484848 channels to record features of the local board situation.

The reason CNNs can help with Go is not that a Go board is literally a photograph. Rather, the task shares useful structural properties with image processing:

  • Many important patterns can be recognized from a limited local region. A stone’s immediate surroundings, for example, can reveal whether it is surrounded or at risk of being captured.
  • The same local pattern can occur at different board locations. A capturing pattern may appear in one corner or another part of the board.

These properties make local receptive fields and shared filters useful. In one described Go network, the first layer uses 5×55 \times 55×5 filters, and later layers use 3×33 \times 33×3 filters. The filters use stride 111 and zero padding, and the network uses a ReLU activation. It does not use pooling.

That omission is important. Pooling is often useful for photographs because a reduced image may still clearly show the same object. A Go position is different: removing rows or columns would alter the board and could erase tactically important details. The right architecture depends on the task, not on a rule that every CNN must contain pooling.

The broader lesson is that architectural choices express assumptions. Local filters and shared parameters fit tasks where useful local patterns recur across positions. Pooling fits tasks where some reduction in spatial detail is acceptable. A component that helps on one task may be inappropriate on another.

Think About It: Why can a local pattern detector be useful for both photographs and Go, while pooling may be suitable for one task but harmful for the other?

Applying CNN ideas beyond images

CNNs have also been applied to speech and text. However, image-oriented choices should not automatically be transferred to those tasks. The arrangement of receptive fields and the way parameters are shared should reflect the structure of the data. Sound and language have different patterns and relationships from images, so their CNN designs may need different assumptions.

A good architecture is not simply one that has worked elsewhere. It is one whose built-in assumptions match the problem being solved.

What CNNs do not automatically handle

CNNs are well suited to detecting local patterns across different image locations, but this does not mean they automatically understand every transformation. In particular, a CNN trained on objects at one scale may not reliably recognize those objects when they are enlarged or reduced. It may also struggle when an object is rotated.

From the network’s point of view, a resized or rotated object changes the arrangement of pixel values. Even if a person sees the same shape, the network may encounter a pattern it has not learned to recognize.

A common response is data augmentation. During training, the system is shown transformed versions of its images—for example, images with crops, different scales, or rotations. This gives it examples of how the target objects can appear under those transformations.

There are also architecture designs intended to handle spatial transformations more directly, including spatial transformer layers. The key point is that scale and rotation robustness do not automatically follow from using a CNN; they must be supported by suitable training examples or architecture choices.

Comprehensive review

A CNN begins with an important observation: images are not just long lists of unrelated numbers. Nearby pixels form local patterns, and the same pattern can appear at different locations. A fully connected network can model images, but its large number of weights can make it expensive and increase the risk of overfitting.

CNNs exploit image structure through two main restrictions. A receptive field limits a neuron to a local region, and parameter sharing lets the same filter detect a pattern at many locations. Together, these ideas form a convolutional layer. Applying each filter across an image produces a feature map, and stacking layers lets the network combine small patterns into larger ones.

Pooling can reduce spatial size and computation, but it can also discard detail, so it is optional and task-dependent. Flattening and fully connected layers provide one traditional route from the final feature maps to class predictions. The same CNN principles can also help with non-image tasks, such as Go, when the task has local patterns that recur across positions—but the architecture must respect the task’s structure. Finally, CNNs do not automatically handle changes in scale or rotation; training transformations or specialized designs may be needed to address those limitations.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent