4. You try to visualize feature maps using this code but get an error:
import matplotlib.pyplot as plt
feature_maps = conv(x)
plt.imshow(feature_maps[0])
plt.show()
What is the likely cause of the error?
medium
A. feature_maps[0] has multiple channels, plt.imshow expects 2D or 3D image
B. conv(x) returns a scalar, not a tensor
C. plt.imshow cannot display tensors
D. x is not defined before conv(x)
Solution
Step 1: Understand feature_maps shape
feature_maps[0] is shape [channels, height, width], multiple channels not a single image.
Step 2: plt.imshow expects 2D or 3D image
plt.imshow needs 2D grayscale or 3D RGB image, but feature_maps[0] has multiple channels causing error.
Final Answer:
feature_maps[0] has multiple channels, plt.imshow expects 2D or 3D image -> Option A
Quick Check:
Multi-channel tensor ≠ single image [OK]
Hint: Plot one channel slice, not full multi-channel tensor [OK]
Common Mistakes:
Trying to plot all channels at once with plt.imshow
Assuming conv output is scalar
Not checking input tensor existence
5. You want to visualize all feature maps from a convolutional layer conv for a single input image x. Which code correctly plots each channel as a separate grayscale image using matplotlib?
hard
A. feature_maps = conv(x)
for i in range(feature_maps.shape[1]):
plt.subplot(1, feature_maps.shape[1], i+1)
plt.imshow(feature_maps[0, i].detach().cpu(), cmap='gray')
plt.show()
B. feature_maps = conv(x)
plt.imshow(feature_maps.detach().cpu(), cmap='gray')
plt.show()
C. feature_maps = conv(x)
for i in range(feature_maps.shape[0]):
plt.imshow(feature_maps[i].detach().cpu(), cmap='gray')
plt.show()
D. feature_maps = conv(x)
plt.imshow(feature_maps[0].detach().cpu())
plt.show()
Solution
Step 1: Extract feature maps and iterate channels
feature_maps shape is [batch, channels, height, width]. We select batch 0 and loop over channels.
Step 2: Plot each channel as grayscale image
Use plt.subplot to arrange images, plt.imshow with cmap='gray' to show each channel properly.
Final Answer:
feature_maps = conv(x)
for i in range(feature_maps.shape[1]):
plt.subplot(1, feature_maps.shape[1], i+1)
plt.imshow(feature_maps[0, i].detach().cpu(), cmap='gray')
plt.show() -> Option A
Quick Check:
Loop channels, plot each with cmap='gray' [OK]
Hint: Loop channels, plot each with grayscale colormap [OK]