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

Study methods

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

Interpreting Neural Networks

Speaker 1Speaker 2

Interpreting Neural Networks

15:02
0:00-15:02
  1. Maria

    Welcome back. In the earlier modules, we worked with convolutional neural networks for images: convolutional layers, max and average pooling, classification networks such as Inception and ResNets, and applications including YOLO, the R-CNN family, face recognition, and neural style transfer.

  2. Corey

    Today we build on that foundation by asking a different question: how can we interpret what a neural network is doing? A lot of network improvement still involves trying architectures, searching hyperparameters, and checking whether a validation score improves. That can work, but it is not very satisfying scientifically unless we also understand why the model made a decision.

  3. Maria

    So the focus is visualization and interpretation. First, we will map an output decision back onto the input image using saliency maps, occlusion sensitivity, and class activation maps. Then we will look inside the network with gradient ascent, class model visualization, dataset search, and deconvolution. If time allows, we will finish with the playful but revealing Deep Dream technique.

  4. Corey

    Let's use a practical example. Suppose we built an animal classifier for a pet shop. It performs extremely well, but the shop owners hesitate to trust it because they cannot tell whether the model is actually looking at the animal or using some accidental background clue.

  5. Maria

    The first quick tool is a saliency map. Suppose the input is an image and we care about the network's dog score. We take the derivative of that score with respect to the input pixels and backpropagate all the way to the image. The result has the same shape as the input: it is a matrix of values telling us how strongly each pixel influenced that particular score.

  6. Corey

    And large absolute values in that matrix identify pixels with a strong effect on the dog score. We can display those values with a color scheme, so bright regions indicate parts of the image that were especially influential. If the strongest values line up with the dog, that gives the pet shop a quick visual explanation.

  7. Maria

    There is an important detail about the score we differentiate. The score of dog should be the value before the softmax, not the final probability, such as 0.85. Softmax takes arbitrary scores, potentially from negative infinity to positive infinity, and converts them into probabilities that sum to one.

  8. Corey

    Why does that distinction matter? A probability can increase because the competing class scores decrease. For example, changing a pixel might reduce the fish score without directly increasing the dog score. That pixel could have a large effect on the post-softmax probability while having little effect on the dog score itself, so the pre-softmax score gives a cleaner representation of what supports the class.

  9. Maria

    Saliency maps can sometimes even be thresholded to produce a rough segmentation of the animal. But they do not work especially well for precise segmentation, so they are mainly a fast way to visualize what the network may be using.

  10. Corey

    The second method is occlusion sensitivity, which is slower but often more precise. We cover a small region of the image with a gray square, run that altered image through the CNN, and record how the class score changes. Then we slide the square across the image, just as a convolutional filter moves across an input.

  11. Maria

    The recorded scores form a probability or confidence map for the class. If covering the dog's face causes the dog probability to fall sharply, that location receives a low-confidence, often blue, value. If covering another region barely changes the score, the network remains confident there, producing a higher, often red, value.

  12. Corey

    Occlusion can even increase a class probability. Removing a distracting object or a competing visual clue may make the network more confident about the target class. The size of the gray square controls the trade-off: a smaller square produces a more spatially precise map, while a larger square gives a coarser result.

  13. Maria

    Some examples make this especially clear. If a Pomeranian has a tennis ball in its mouth, covering the ball can reduce the Pomeranian confidence because the tennis ball was associated with another class. Conversely, covering a human face in an image of a dog can increase the dog confidence if the visible face was making the network lean toward a human class.

  14. Corey

    The third input-focused method is the class activation map, or CAM. The key idea is that a classification CNN can retain useful localization information even when it was trained only with image-level labels, not bounding boxes or segmentation masks.

  15. Maria

    A standard classifier often flattens the final convolutional volume and sends it through fully connected layers. Flattening removes the explicit spatial arrangement, making it difficult to determine where an activation came from. CAM replaces that final flattening and fully connected structure with global average pooling followed by a fully connected softmax layer.

  16. Corey

    Imagine the last convolution produces a four-by-four-by-six volume. The six channels are six feature maps. Global average pooling averages each four-by-four feature map into one number, producing a six-value vector. Each value summarizes how strongly one learned visual pattern appeared across the feature map.

  17. Maria

    The final fully connected layer has a different weight for each feature-map activation and each class. To make a dog CAM, we take the dog-related weights and form a weighted sum of the six feature maps. A feature map with a large positive dog weight contributes more strongly to that sum, so the resulting map highlights locations containing patterns that support the dog class.

  18. Corey

    That weighted map is still smaller than the original image because it comes from the last convolutional layer. We upsample it to the input size and overlay it on the image. It is called a class activation map because the weights, and therefore the highlighted locations, depend on the class: the map for human would use different weights from the map for dog.

  19. Maria

    Global averaging does not destroy all spatial information in this setup. The feature maps still retain their locations, and the algebra lets us rearrange the sums: for each spatial location, we take the weighted combination across channels, then consider those local class scores across the map. That is why the final weighted feature map can still show where the class evidence occurred.

  20. Corey

    CAM requires a small modification and fine-tuning of the final layers, but it can then provide a clear localization explanation. Saliency maps use gradients all the way to pixels, whereas CAM uses the last convolutional feature maps and their class-specific weights; it is not simply the same backpropagation calculation.

  21. Maria

    Now we move inside the network. The pet shop may accept that the model is looking at the right place, but ask a deeper question: what does the model think a dog actually is? For that, we can use gradient ascent, also called class model visualization.

  22. Corey

    We define an objective based on the dog score, usually with a regularization term encouraging the image to remain natural. We start with an image, forward-propagate it, compute the objective, backpropagate its gradient to the pixels, and update the pixels in the direction that increases the objective. Repeating this process produces an image that maximizes what the network considers evidence for dog.

  23. Maria

    The same procedure can be applied to a class such as goose, ostrich, kit fox, husky, or dalmatian. The resulting images reveal patterns the network associates with those classes, although the raw results can be difficult to interpret. For a dalmatian, for example, we might see dark spots on a light background.

  24. Corey

    Regularization is essential because the optimization is not automatically restricted to valid image pixels. L2-style regularization discourages extreme pixel values, and we may also clip values to the image range of zero to 255. Gaussian blurring adds another useful regularizer by discouraging rapid, high-frequency changes from one pixel to the next.

  25. Maria

    With stronger regularization, the visualizations can become more recognizable. One surprising result is that maximizing the flamingo score may produce several flamingos, because the network can assign a higher flamingo score to many flamingos than to one. The method is useful for understanding what features the model has learned, but a realistic-looking visualization alone does not directly prove that the model is more accurate.

  26. Corey

    We can also maximize an intermediate activation instead of a final class score. That reveals what a particular neuron or feature map responds to, independent of a single output class. In many ways, this gives a more detailed picture of the network's internal representation.

  27. Maria

    A second internal method is dataset search. Choose one feature map at a particular layer, run many dataset images through the network, and find the images that produce the largest activation in that feature map. The top examples may reveal that one feature detects shirts, while another detects edges.

  28. Corey

    The layer matters. Early features often respond to simple edges or colors, while deeper features combine those patterns into more complex concepts. Dataset search can also show why the examples are cropped: an activation in a convolutional layer usually sees only a receptive field, a subregion of the original image.

  29. Maria

    You can determine that receptive field by tracing the filter sizes, strides, and pooling operations back through the network. An activation near the beginning sees a small input region. As we move deeper, each activation depends on a larger portion of the original image, so deeper units can respond to broader structures.

  30. Corey

    The third internal tool is deconvolution, which reconstructs an activation back into input space. It is useful for understanding what a selected activation fired for, and it is also important in applications such as segmentation, where an encoded representation must be upsampled into a mask with the original image dimensions.

  31. Maria

    For visualization, we select one feature map, keep its strongest activation, and set the other activations to zero. Then we work backward through the pooling, ReLU, and convolution operations. The reconstruction is cropped because that activation only saw its receptive field, so it might reveal just the dog's ears rather than the complete image.

  32. Corey

    The mathematical intuition begins with a one-dimensional convolution. A convolution can be written as a matrix multiplied by an input vector: y equals W times x. The matrix contains shifted copies of the filter, with zeros where the filter does not touch the input. For an input of length twelve, a filter of length four, stride two, and padding two, the output has length five.

  33. Maria

    If W is invertible, we could write x as W inverse times y and reconstruct the input. In practice, for visualization, we use the existing convolutional weights rather than training a separate inverse network, and we often make an orthogonality assumption as an approximation. For an orthogonal matrix, the inverse is the transpose, so the reconstruction uses a transposed version of W.

  34. Corey

    This reconstruction is not necessarily exact because the assumptions do not always hold. That is acceptable for visualization because we want a useful picture of what activated the unit. In segmentation or other upsampling tasks, we can instead train the deconvolution weights directly, so the orthogonality assumption is not required.

  35. Maria

    Another way to implement the same operation is sub-pixel convolution. Insert zeros between elements of the smaller representation, flip the filter weights, reduce the stride, and apply an ordinary convolution. In two dimensions, each value in the smaller feature map spreads the filter's contribution over a larger output area, and overlapping contributions are added together.

  36. Corey

    Pooling and ReLU also need reverse operations. Max pooling is not mathematically invertible because it keeps only the maximum and discards the other values. We can approximate the inverse by caching switches: a matrix indicating where each maximum occurred, then placing each pooled value back at that location.

  37. Maria

    For ordinary ReLU backpropagation, negative inputs receive zero gradient because their values had no influence on the forward output. In the deconvolution-style visualization, we use a related reconstruction rule that keeps positive contributions while trying to show which pixels positively affected the selected activation. This is a visualization choice rather than a guaranteed exact inverse.

  38. Corey

    When these tools are applied across layers, the progression is revealing. Filters in the first layer can often be interpreted directly as edge or color detectors, because their weights multiply raw pixels. In deeper layers, the filters themselves become difficult to interpret, but the images that maximize their activations can reveal circles, faces, clothing, wrinkles, or printed text.

  39. Maria

    Those features were not explicitly labeled during training. The network learned them because they helped support the final classification decisions. For example, detecting text may help identify a book, and detecting multiple books may help identify a bookcase. Visualization exposes these internal concepts even though the training labels were provided only at the output.

  40. Corey

    The same visualizations can also reveal inactive or dead feature maps. If a feature map remains dark for every input, the filter that created it may not be detecting anything useful, which suggests that part of the network is not being effectively trained.

  41. Maria

    Finally, there is Deep Dream. At a chosen layer, we forward-propagate an image, take the activations at that layer, set the gradient there equal to those activations, and backpropagate to update the input pixels. Repeating this strengthens patterns the network already detects, causing objects or textures to emerge.

  42. Corey

    If a cloud vaguely resembles a dog, the process can strengthen the dog-like activation until a more recognizable dog appears. Lower layers tend to produce edges and simple patterns, while deeper layers can produce animals, towers, or other complex forms. The results become surreal because the method repeatedly amplifies the network's own interpretations.

  43. Maria

    Deep Dream also exposes the context learned by the model. If the network has mostly seen dumbbells held by people, maximizing the dumbbell score may produce a hand and a dumbbell rather than an isolated weight. The model has learned the visual context that commonly accompanies the object.

  44. Corey

    So the methods answer different questions. Saliency maps, occlusion sensitivity, and class activation maps ask which parts of an input supported a particular output. Dataset search, gradient ascent, and deconvolution ask what a neuron or feature layer responds to and how the network represents visual concepts.

  45. Maria

    They also have practical uses: checking whether a model focuses on the correct evidence, obtaining rough localization, supporting segmentation and reconstruction, visualizing generated images, and finding inactive neurons. For non-image data, analogous interpretation methods exist; for example, attention models can indicate which parts of a sentence mattered for an output.

  46. Corey

    The larger lesson is that interpretation gives us more than a final accuracy number. It helps us inspect the decision process, understand intermediate representations, identify shortcuts or unwanted context, and develop better intuition for how convolution, pooling, activation functions, and upsampling work together.

  47. Maria

    Exactly. Once we can connect a prediction back to the input and inspect what individual neurons detect, neural networks become less of a black box. The explanations are approximations, and some require assumptions or regularization, but together these tools provide a much stronger scientific view of the model than trial and error alone.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent