cu.viz: data and CNN visualization
Visualize image data and CNNs: sample grids, Grad-CAM, activations, feature maps.
Image data
- colabutilscs4337.viz.show_by_class(images, labels=None, classes=None, *, n_per_class=8, size=1.0, max_scan=5000, seed=None, mean=None, std=None, pad=2, title=None)[source]
One row per class with
n_per_classexamples each; class names on the left.- Parameters:
images (Any) – A batch tensor
B x C x H x Wwithlabels, an(x, y)batch, aDataLoader, or aDataset(up tomax_scanrandom items are scanned to fill every row).labels (Any) – Class indices
(B,)or(B, 1)whenimagesis a tensor.classes (Sequence[str] | Mapping[int, str] | None) – Class names (list or dict). Defaults to
dataset.classesor the label numbers. Classes with no examples get an empty row.n_per_class (int) – Examples per row and inches per image.
size (float) – Examples per row and inches per image.
max_scan (int)
seed (int | None)
pad (int)
title (str | None)
- Returns:
matplotlib.figure.Figure
Examples
>>> cu.viz.show_by_class(train_ds) # every class, 8 examples each >>> cu.viz.show_by_class(x, y, labels_map, n_per_class=5)
- colabutilscs4337.viz.show_images(images, labels=None, classes=None, *, preds=None, n=32, ncols=8, size=1.6, shuffle=True, seed=None, mean=None, std=None, title=None)[source]
Show images in a grid, with class names (and predictions) as titles.
- Parameters:
images (Any) – A batch tensor
B x C x H x W, an(x, y)batch, aDataset(samplesnrandom items), aDataLoader(shows its first batch), a list of PIL images/arrays/tensors, or a fastaiDataLoaders(uses itsshow_batch).labels (Any) – Class indices, shape
(B,)or(B, 1). Not needed for datasets/loaders.classes (Sequence[str] | Mapping[int, str] | None) – Class names: a list (
train_ds.classes) or a dict{0: "T-Shirt", ...}. Taken fromdataset.classesautomatically when available.preds (Any) – Predicted class indices. Titles become
pred / true(red when wrong).n (int) – Number of images, images per row, and inches per image.
ncols (int) – Number of images, images per row, and inches per image.
size (float) – Number of images, images per row, and inches per image.
shuffle (bool) – Random sample from a Dataset (
seedmakes it repeatable).seed (int | None) – Random sample from a Dataset (
seedmakes it repeatable).mean – Undo normalization, e.g.
mean=cu.viz.IMAGENET_MEAN, std=cu.viz.IMAGENET_STD.std – Undo normalization, e.g.
mean=cu.viz.IMAGENET_MEAN, std=cu.viz.IMAGENET_STD.title (str | None)
- Returns:
matplotlib.figure.Figure
Examples
>>> train_ds = torchvision.datasets.FashionMNIST("data", download=True, ... transform=transforms.ToTensor()) >>> cu.viz.show_images(train_ds) # 32 random samples >>> x, y = next(iter(train_loader)) >>> cu.viz.show_images(x, y, train_ds.classes, n=16) >>> cu.viz.show_images(x, y, train_ds.classes, preds=model(x).argmax(1))
- colabutilscs4337.viz.tensor_to_image(*imgtensor, dim=2, pad=0, mean=None, std=None)[source]
Turn one or more image tensors into a single
PIL.Imagestrip.- Parameters:
*imgtensor (torch.Tensor) – One or more tensors, each
C x H x Wor a batchB x C x H x W. Values in[0, 1],uint8in[0, 255], or normalized (passmean/std, or values are min-max rescaled).dim (int) – How images are joined:
2(default) puts them side by side (a row),1stacks them top to bottom (a column).pad (int) – White pixels between images.
mean (sequence of float, optional) – Undo
Normalize(mean, std), e.g.cu.viz.IMAGENET_MEAN/IMAGENET_STD.std (sequence of float, optional) – Undo
Normalize(mean, std), e.g.cu.viz.IMAGENET_MEAN/IMAGENET_STD.
- Returns:
PIL.Image.Image – Grayscale (
"L") for 1-channel input, otherwise RGB.
Examples
>>> cu.viz.tensor_to_image(x[:8]) # first 8 images of a batch, in a row >>> cu.viz.tensor_to_image(x[:8], dim=1) # ... as a column >>> cu.viz.tensor_to_image(img_a, img_b) # two images side by side
- colabutilscs4337.viz.to_image(image, mean=None, std=None)[source]
Convert an image to a float
HxWx3array in[0, 1].Accepts a PIL image, an
HxWx3array, or a(3,H,W)/(1,3,H,W)tensor. Passmean/std(for exampleIMAGENET_MEAN/IMAGENET_STD) to undo normalization; otherwise values outside[0, 1]are min-max rescaled.- Parameters:
image (Any)
mean (Sequence[float] | None)
std (Sequence[float] | None)
Grad-CAM
- colabutilscs4337.viz.gradcam(model, x, target_layer=None, class_idx=None, *, method='gradcam')[source]
Class activation map for a batch
xof shape(B, 3, H, W).class_idxdefaults to the predicted class.target_layeris a dotted name ("layer4") or module; it defaults tosuggest_target_layer().methodis"gradcam"(built in) or one ofgradcam++,xgradcam,hirescam,layercam,scorecam,eigencam,ablationcam(needscu.install("cam")).- Parameters:
model (Any)
x (Any)
target_layer (Any | None)
class_idx (int | Sequence[int] | None)
method (str)
- Return type:
- class colabutilscs4337.viz.CAMResult(cams, class_idx, scores, layer, method)[source]
Bases:
objectGrad-CAM output.
camsis(B, H, W)in[0, 1]at the input resolution.- Parameters:
cams (Any)
class_idx (list[int])
scores (list[float])
layer (str)
method (str)
- property cam
The first (often only) heatmap, shape
(H, W).
- colabutilscs4337.viz.show_cam(image, cam, *, alpha=0.5, cmap='jet', title=None, ax=None, side_by_side=True, show_color_bar=True, **image_kwargs)[source]
Show the image and its CAM overlay.
camis aCAMResultor(H, W)heatmap.show_color_baradds a 0-1 importance scale next to the overlay (CAMs are normalized to 0-1 per image). Passaxto draw only the overlay into your own axes.Examples
>>> cu.viz.show_cam(img, cam) # input | overlay + color bar >>> cu.viz.show_cam(img, cam, show_color_bar=False, side_by_side=False)
- Parameters:
image (Any)
cam (Any)
alpha (float)
cmap (str)
title (str | None)
ax (Any)
side_by_side (bool)
show_color_bar (bool)
- colabutilscs4337.viz.overlay(image, cam, alpha=0.5, cmap='jet', **image_kwargs)[source]
Blend a heatmap onto an image; returns an
HxWx3float array.- Parameters:
image (Any)
cam (Any)
alpha (float)
cmap (str)
- colabutilscs4337.viz.suggest_target_layer(model, x=None)[source]
Name of a good Grad-CAM layer: the last module with a spatial (H, W > 1) output.
With an example input
xthis is found by tracing a forward pass (works for torchvision ResNets ->"layer4", fastaivision_learner->"0", timm, and custom CNNs). Withoutxthe lastnn.Conv2dis returned.- Parameters:
model (Any)
x (Any | None)
- Return type:
str
Activations
- colabutilscs4337.viz.activations(model, x, layers=None, *, detach=True)[source]
Run
model(x)and return{layer_name: output}for the requested layers.layersdefaults to everynn.Conv2d. Outputs are detached and moved to CPU unlessdetach=False.- Parameters:
model (Any)
x (Any)
layers (Iterable[Any] | None)
detach (bool)
- Return type:
dict[str, Any]
- colabutilscs4337.viz.show_feature_maps(act, n=16, *, ncols=8, sample=0, cmap='viridis', title=None)[source]
Grid of the first
nchannels of an activation(B, C, H, W)or(C, H, W).- Parameters:
act (Any)
n (int)
ncols (int)
sample (int)
cmap (str)
title (str | None)
Constants
- colabutilscs4337.viz.IMAGENET_MEAN = (0.485, 0.456, 0.406)
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.
If the argument is a tuple, the return value is the same object.
- colabutilscs4337.viz.IMAGENET_STD = (0.229, 0.224, 0.225)
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.
If the argument is a tuple, the return value is the same object.