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

Study methods

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

Visualizing Convolutional Networks

Speaker 1Speaker 2

Visualizing Convolutional Networks

18:01
0:00-18:01
  1. Simon

    Welcome to Lecture 12: visualizing and understanding convolutional networks. We’ve learned how to train ConvNets and connect their layers to solve different tasks, but they can still feel like a black box. Today we’ll look at ways to inspect what they learn and what information they use.

  2. Michael

    And the motivation is important: a network can produce a class score, bounding box, or segmentation, but we’d like some intuition for what is happening between the pixels and that output. We’ll use visualizations based on weights, activations, gradients, and generated images.

  3. Simon

    Before we get into that, a few course notes from the lecture: project milestones were due on Canvas that night, midterm grading was underway on Gradescope, and Assignment 3 had been released with a choice of PyTorch or TensorFlow. The HyperQuest extra-credit deadline had also been extended, and the poster session date was set for June 6.

  4. Michael

    For context, last lecture covered several vision tasks. Semantic segmentation labels every pixel but doesn’t distinguish object instances. Classification plus localization predicts a class and a fixed set of locations, while object detection finds every instance of selected categories even when the number of instances is unknown.

  5. Simon

    And instance segmentation combines detection with pixel labeling: find each object instance and identify the pixels belonging to it. Those tasks give us examples of what a network’s final output can mean. Today we’ll turn inward and ask what the network’s internal representations are doing.

  6. Michael

    Let’s start with the first convolutional layer. In AlexNet, for example, a filter has dimensions three by eleven by eleven: three color channels and an eleven-by-eleven spatial patch. The filter slides over the image, and at each location an inner product between its weights and the image patch produces an activation.

  7. Simon

    Because those first-layer weights act directly on RGB pixels, we can visualize each filter as a small color image. Looking across the filters, we often see oriented edges, bars, and opposing colors—like orange and blue or green and pink.

  8. Michael

    That resembles early stages of the human visual system, which also respond to oriented edges. And this pattern tends to show up across many image ConvNets, even with different architectures or training data.

  9. Simon

    Why does visualizing a filter tell us what it responds to? Think about an inner product between a template and an input patch. Under a norm constraint, the patch that maximizes the response is the one that aligns with the template. So the weights give us a rough picture of the pattern that excites the filter.

  10. Michael

    But the same trick is much less informative in intermediate layers. Those filters operate on the previous layer’s feature maps, not directly on image pixels. If a filter has sixteen input channels, flattening its weights into a collection of grayscale pictures doesn’t clearly reveal what image pattern it represents.

  11. Simon

    There are caveats even for first-layer pictures: weights may need to be rescaled to display them, and the visualization doesn’t include the layer’s biases. So we should treat it as useful intuition, not a complete description of the computation.

  12. Michael

    Another route is to inspect the final hidden representation. Take an image, pass it through a trained network, and record its 4096-dimensional feature vector just before the class scores. Then compare images by their distance in that feature space.

  13. Simon

    That gives a useful contrast with nearest neighbors in raw pixel space. Pixel neighbors often look alike in color and layout. Feature-space neighbors can have very different pixels but similar semantic content—for instance, an elephant facing the other way can still be close to the query elephant.

  14. Michael

    That semantic organization is a consequence of training for classification, even though ordinary classification training doesn’t explicitly tell the network to make similar images close together. Other approaches, such as contrastive or triplet losses, can impose that kind of metric structure directly.

  15. Simon

    We can also reduce the feature dimension to visualize its geometry. PCA is one familiar method, and t-SNE—t-distributed stochastic neighbor embedding—is a nonlinear dimensionality-reduction method often used to visualize learned features.

  16. Michael

    For example, applying t-SNE to handwritten-digit pixels can reveal clusters corresponding to digits. We can also run images through an ImageNet classifier, reduce their feature vectors to two dimensions, and place representative images on a grid. That gives a rough sense of semantic neighborhoods in the learned space.

  17. Simon

    It’s only a rough view, though. A two-dimensional plot can hide overlaps and density, and t-SNE doesn’t give us a simple variance-explained interpretation like PCA. It’s a visualization aid, not a full map of the feature space.

  18. Michael

    We can inspect intermediate activations too. A convolutional layer produces an activation volume—a three-dimensional block of numbers. Each channel is an activation map, a two-dimensional grid showing where one learned feature responds.

  19. Simon

    In AlexNet’s conv5 layer, for example, each image gives a collection of 13-by-13 maps. Visualizing those maps can reveal where a particular feature is active. An interactive webcam demo showed one channel responding strongly around a person’s face.

  20. Michael

    That doesn’t necessarily mean the network was trained with ‘human face’ as a class. People occur in training images and can provide useful signals for recognizing other categories. A feature can be useful to the task without corresponding to an explicit output label.

  21. Simon

    Also, a dark or inactive map for one image isn’t what we usually mean by a dead ReLU. That term generally refers to a unit that stays inactive across the training data. And activation-map size may differ from image size because of stride, pooling, or other downsampling.

  22. Michael

    A related technique is to find maximally activating patches. Choose a feature channel, run many images through the network, and locate the image patches associated with its largest activations.

  23. Simon

    Those patches can suggest what the feature responds to. A set might contain circles and eyes, colored text, or curved edges. At higher layers, receptive fields are larger, so the selected patches may reveal more complex structures, such as faces or object parts.

  24. Michael

    Because the network is convolutional, a channel’s filter is shared across spatial positions. We’re not saying there’s only one response in the image: many individual spatial activations use the same channel’s weights, and their strongest patches can come from different locations.

  25. Simon

    We can also ask which image regions matter for a particular classification using occlusion. Cover a small region—often replacing it with the dataset’s mean pixel value—run the altered image through the network, and record the class probability.

  26. Michael

    Slide that occluding patch across the image and plot the results. If covering a region sharply lowers the target-class score, that region was important to the prediction. In the lecture’s go-kart example, masking the kart caused the go-kart probability to drop.

  27. Simon

    Occlusion is a tool for human understanding, not necessarily a direct way to improve training. And interpretation can be complicated: background objects or scene context may also affect the score, so a heat map doesn’t always isolate one clean cause.

  28. Michael

    Saliency maps offer a gradient-based answer to a similar question. Compute the gradient of the predicted class score with respect to the input pixels. That gradient estimates how much the score would change if each pixel changed slightly.

  29. Simon

    For a dog image, the resulting map can outline the dog, suggesting that those pixels influence the class score. Saliency has also been combined with interactive segmentation methods such as GrabCut to help isolate objects, although that approach can be brittle and generally isn’t a substitute for a network trained with segmentation labels.

  30. Michael

    We can ask the same question about an internal neuron rather than a class score: which pixels influence that neuron’s activation? Ordinary backpropagation can compute the gradient. Guided backpropagation modifies how gradients pass through ReLUs, keeping positive gradients and discarding negative ones.

  31. Simon

    That modification is not the true gradient, but it often produces cleaner-looking visualizations. Combined with maximally activating patches, it can highlight the parts of a patch that influence a feature—say, the circular portion of an image that appears to activate a circle-like neuron.

  32. Michael

    Saliency and guided backpropagation explain influences for a particular input. A different question is: what input would activate a chosen neuron or class in general? We can answer by fixing the trained network and optimizing the image pixels to increase that score.

  33. Simon

    The basic procedure is gradient ascent. Start from an image—perhaps zeros or random noise—run it through the network, compute the target score’s gradient with respect to the pixels, update the pixels in the direction that increases the score, and repeat.

  34. Michael

    Without regularization, that can produce an image the network classifies confidently but that looks like noise. So we add a preference for natural-looking images. A simple early choice was an L2 penalty on the image, though it often yielded messy, superimposed patterns.

  35. Simon

    The generated images can also be mult imodal: a class may be represented by quite different visual patterns. More sophisticated regularization can improve clarity—for example, periodically blurring the image, clipping small pixel values, or suppressing pixels with small gradients.

  36. Michael

    Those operations act like projections toward images with preferred properties, such as spatial smoothness. They can make a flamingo, beetle, or billiard table more recognizable. Still, displayed colors and values need care: valid images have bounded pixel ranges, while unconstrained gradient ascent may not.

  37. Simon

    Some work addresses multimodality more directly by clustering examples within a class and initializing optimization near different clusters. Grocery-store images, for example, can show produce close-ups or people shopping—both the same class, but visually quite different.

  38. Michael

    Stronger image priors can produce even more realistic visualizations. One approach optimizes a network representation rather than raw pixels and uses a feature-inversion network to turn that representation back into an image. The key idea is that richer models of natural images can make the result more informative.

  39. Simon

    Gradient-based image optimization also reveals a surprising weakness: fooling images. Start with an elephant, then adjust pixels to make the network predict ‘koala bear.’ The resulting image can still look like an elephant to a person, even though the network assigns it the koala class.

  40. Michael

    Likewise, a boat can be changed by a small pixel perturbation so the classifier calls it an iPod. The difference may look like noise rather than meaningful iPod features. This connects to adversarial examples, a topic the lecture noted would be developed further in a guest lecture.

  41. Simon

    Why study all these visualizations? One criticism of deep learning is that it can be hard to understand why a complicated model makes a decision. These methods don’t make every decision fully interpretable, but they can show that internal features respond to meaningful structures and can expose surprising behavior.

  42. Michael

    DeepDream is a particularly vivid example. Run an image through a network to some layer, then backpropagate that layer’s activations as a signal to increase them. Repeating the process amplifies features the network already detected in the image.

  43. Simon

    Practical versions may jitter the image before computing gradients, normalize gradients, and clip pixel values. Those choices help regularize the process. Starting from a sky, for example, can lead to amplified shapes that resemble animals, buildings, or other patterns.

  44. Michael

    The results often contain dogs. That’s not so mysterious when you remember that ImageNet includes many dog categories—about two hundred in the lecture’s account. A network trained on a scene dataset instead may emphasize architecture, bridges, or mountains.

  45. Simon

    Lower layers tend to produce simpler edges and swirls; higher layers produce more complex patterns. Running DeepDream at multiple image scales can create especially elaborate images. It’s largely an artistic experiment, but it also gives us clues about the kinds of features the network detects.

  46. Michael

    Feature inversion asks a related but different question: how much of an image is represented at a particular network layer? Pass an image through the network, save its features at a chosen layer, then optimize a new image to match those features.

  47. Simon

    A total-variation regularizer is often used here. It penalizes differences between neighboring pixels, encouraging spatial smoothness. With features from a relatively early layer, the reconstruction can be nearly exact; with deeper features, broad layout and object identity may remain while colors, textures, and pixel-level details change.

  48. Michael

    That suggests deeper representations discard some low-level detail and preserve more semantic, less locally sensitive information. It leads naturally to another topic: texture synthesis.

  49. Simon

    Texture synthesis means taking a small sample—say, a patch of scales or rocks—and generating a larger image that has similar texture. Classical nearest-neighbor methods can work for simple textures by filling pixels in scan-line order using nearby generated pixels and patches from the sample.

  50. Michael

    But copying pixels this way struggles with more complex textures. A neural approach uses convolutional features to describe texture. For an input image, take the feature maps at a layer and form a Gram matrix from their feature vectors.

  51. Simon

    More precisely, the feature map has spatial positions and a channel vector at each position. The outer products of channel vectors, averaged across spatial positions, give a channel-by-channel Gram matrix. It captures which features tend to co-occur, while discarding their exact locations.

  52. Michael

    That loss of spatial arrangement is useful for texture: we care about feature statistics, not reproducing the same object layout. The matrix can be computed efficiently by reshaping the feature volume and multiplying it by its transpose. Covariance-based alternatives are possible, but Gram matrices are commonly used.

  53. Simon

    To synthesize texture, compute Gram matrices for the sample, start with a random image, and optimize its pixels so its Gram matrices match. Often the loss combines Gram-matrix comparisons from several network layers.

  54. Michael

    Different layers capture different scales. Lower-layer matching tends to reproduce broad color and small local patterns; higher-layer matching can reproduce larger structures, like whole rocks or cranberries. The output can have similar texture statistics without copying the original pixels.

  55. Simon

    Now combine texture synthesis with feature inversion and we get neural style transfer. We use a content image to specify what the picture should depict and a style image to specify its texture or artistic appearance.

  56. Michael

    The generated image is optimized to match the content image’s features and the style image’s Gram matrices. Start from noise, compute both losses, backpropagate to the image pixels, and repeat. The result can preserve the content while rendering it in the style of a painting.

  57. Simon

    We can control the trade-off by changing the weights on content and style losses. Resizing the style image before computing its Gram matrices also changes the scale of patterns we transfer. And matching multiple style images can blend styles.

  58. Michael

    Multi-scale processing can extend style transfer to high-resolution images, although it is computationally expensive. It’s also possible to combine content and style objectives with a DeepDream objective, producing images that retain content and style while amplifying network features.

  59. Simon

    The original optimization-based style-transfer process is slow because it requires many forward and backward passes for every image. A faster approach trains a feed-forward network to produce a stylized result directly from a content image.

  60. Michael

    During training, that network is optimized using the same content and style losses. Training can take hours, but once the network is trained, stylization requires only one forward pass and can run in real time.

  61. Simon

    The architecture resembles image-to-image networks: downsampling, processing layers, then upsampling to produce an RGB image. Instance normalization, used instead of batch normalization in the described approach, gave better results.

  62. Michael

    One limitation is that the first fast method needed a separate trained network for each style. Later work used one network that accepts both the content image and a chosen style, enabling multiple styles—and even style blending—at test time.

  63. Simon

    So we’ve seen two broad families of tools. Activation-based methods include nearest neighbors, dimensionality reduction, activation maps, maximally activating patches, and occlusion. Gradient-based methods include saliency, guided backpropagation, image synthesis, feature inversion, and adversarial or fooling-image experiments.

  64. Michael

    And the same ideas support creative applications such as DeepDream, texture synthesis, and style transfer. They don’t turn a ConvNet into a perfectly transparent system, but they help us examine what its representations capture, what influences its predictions, and where its behavior can be unexpected.

  65. Simon

    That’s the main lesson: visualizations are tools for forming and testing intuition, and each one answers a different question. Next time, the course moves to unsupervised learning, including autoencoders, variational autoencoders, and generative adversarial networks.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent