Book Utils

Pieces of code we can re-use between chapters

If we’d like, we can export code from here to use throughout the book…


source

show_images

 show_images (ims:list, nrows:Optional[int]=None,
              ncols:Optional[int]=None, titles:Optional[list]=None,
              figsize:tuple=None, imsize:int=3, suptitle:str=None,
              sharex=False, sharey=False, squeeze=True, width_ratios=None,
              height_ratios=None, subplot_kw=None, gridspec_kw=None)

Show all images ims as subplots with rows using titles

Type Default Details
ims list Images to show
nrows typing.Optional[int] None Number of rows in grid
ncols typing.Optional[int] None Number of columns in grid (auto-calculated if None)
titles typing.Optional[list] None Optional list of titles for each image
figsize tuple None Width, height in inches of the returned figure
imsize int 3 Size (in inches) of images that will be displayed in the returned figure
suptitle str None Title to be set to returned figure
sharex bool False
sharey bool False
squeeze bool True
width_ratios NoneType None
height_ratios NoneType None
subplot_kw NoneType None
gridspec_kw NoneType None

source

get_grid

 get_grid (n:int, nrows:int=None, ncols:int=None, title:str=None,
           weight:str='bold', size:int=14, figsize:tuple=None,
           imsize:int=3, suptitle:str=None, sharex=False, sharey=False,
           squeeze=True, width_ratios=None, height_ratios=None,
           subplot_kw=None, gridspec_kw=None)

Return a grid of n axes, rows by cols

Type Default Details
n int Number of axes
nrows int None Number of rows, defaulting to int(math.sqrt(n))
ncols int None Number of columns, defaulting to ceil(n/rows)
title str None If passed, title set to the figure
weight str bold Title font weight
size int 14 Title font size
figsize tuple None Width, height in inches of the returned figure
imsize int 3 Size (in inches) of images that will be displayed in the returned figure
suptitle str None Title to be set to returned figure
sharex bool False
sharey bool False
squeeze bool True
width_ratios NoneType None
height_ratios NoneType None
subplot_kw NoneType None
gridspec_kw NoneType None

source

subplots

 subplots (nrows:int=1, ncols:int=1, figsize:tuple=None, imsize:int=3,
           suptitle:str=None, sharex=False, sharey=False, squeeze=True,
           width_ratios=None, height_ratios=None, subplot_kw=None,
           gridspec_kw=None, **kwargs)

A figure and set of subplots to display images of imsize inches

Type Default Details
nrows int 1 Number of rows in returned axes grid
ncols int 1 Number of columns in returned axes grid
figsize tuple None Width, height in inches of the returned figure
imsize int 3 Size (in inches) of images that will be displayed in the returned figure
suptitle str None Title to be set to returned figure
sharex bool False
sharey bool False
squeeze bool True
width_ratios NoneType None
height_ratios NoneType None
subplot_kw NoneType None
gridspec_kw NoneType None
kwargs
/opt/hostedtoolcache/Python/3.9.16/x64/lib/python3.9/site-packages/fastcore/docscrape.py:225: UserWarning: Unknown section Other Parameters
  else: warn(msg)
/opt/hostedtoolcache/Python/3.9.16/x64/lib/python3.9/site-packages/fastcore/docscrape.py:225: UserWarning: Unknown section See Also
  else: warn(msg)
/opt/hostedtoolcache/Python/3.9.16/x64/lib/python3.9/site-packages/fastcore/docscrape.py:225: UserWarning: Unknown section Notes
  else: warn(msg)

source

show_image

 show_image (im, ax=None, figsize=None, title=None, noframe=True,
             cmap=None, norm=None, aspect=None, interpolation=None,
             alpha=None, vmin=None, vmax=None, origin=None, extent=None,
             interpolation_stage=None, filternorm=True, filterrad=4.0,
             resample=None, url=None, data=None)

Show a PIL or PyTorch image on ax.

Type Default Details
im
ax NoneType None
figsize NoneType None
title NoneType None
noframe bool True
cmap NoneType None The Colormap instance or registered colormap name used to map scalar data
to colors.

This parameter is ignored if X is RGB(A).
norm NoneType None The normalization method used to scale scalar data to the [0, 1] range
before mapping to colors using cmap. By default, a linear scaling is
used, mapping the lowest value to 0 and the highest to 1.

If given, this can be one of the following:

- An instance of .Normalize or one of its subclasses
(see :doc:/tutorials/colors/colormapnorms).
- A scale name, i.e. one of “linear”, “log”, “symlog”, “logit”, etc. For a
list of available scales, call matplotlib.scale.get_scale_names().
In that case, a suitable .Normalize subclass is dynamically generated
and instantiated.

This parameter is ignored if X is RGB(A).
aspect NoneType None The aspect ratio of the Axes. This parameter is particularly
relevant for images since it determines whether data pixels are
square.

This parameter is a shortcut for explicitly calling
.Axes.set_aspect. See there for further details.

- ‘equal’: Ensures an aspect ratio of 1. Pixels will be square
(unless pixel sizes are explicitly made non-square in data
coordinates using extent).
- ‘auto’: The Axes is kept fixed and the aspect is adjusted so
that the data fit in the Axes. In general, this will result in
non-square pixels.
interpolation NoneType None The interpolation method used.

Supported values are ‘none’, ‘antialiased’, ‘nearest’, ‘bilinear’,
‘bicubic’, ‘spline16’, ‘spline36’, ‘hanning’, ‘hamming’, ‘hermite’,
‘kaiser’, ‘quadric’, ‘catrom’, ‘gaussian’, ‘bessel’, ‘mitchell’,
‘sinc’, ‘lanczos’, ‘blackman’.

If interpolation is ‘none’, then no interpolation is performed
on the Agg, ps, pdf and svg backends. Other backends will fall back
to ‘nearest’. Note that most SVG renderers perform interpolation at
rendering and that the default interpolation method they implement
may differ.

If interpolation is the default ‘antialiased’, then ‘nearest’
interpolation is used if the image is upsampled by more than a
factor of three (i.e. the number of display pixels is at least
three times the size of the data array). If the upsampling rate is
smaller than 3, or the image is downsampled, then ‘hanning’
interpolation is used to act as an anti-aliasing filter, unless the
image happens to be upsampled by exactly a factor of two or one.

See
:doc:/gallery/images_contours_and_fields/interpolation_methods
for an overview of the supported interpolation methods, and
:doc:/gallery/images_contours_and_fields/image_antialiasing for
a discussion of image antialiasing.

Some interpolation methods require an additional radius parameter,
which can be set by filterrad. Additionally, the antigrain image
resize filter is controlled by the parameter filternorm.
alpha NoneType None The alpha blending value, between 0 (transparent) and 1 (opaque).
If alpha is an array, the alpha blending values are applied pixel
by pixel, and alpha must have the same shape as X.
vmin NoneType None
vmax NoneType None
origin NoneType None Place the [0, 0] index of the array in the upper left or lower
left corner of the Axes. The convention (the default) ‘upper’ is
typically used for matrices and images.

Note that the vertical axis points upward for ‘lower’
but downward for ‘upper’.

See the :doc:/tutorials/intermediate/imshow_extent tutorial for
examples and a more detailed description.
extent NoneType None The bounding box in data coordinates that the image will fill.
These values may be unitful and match the units of the Axes.
The image is stretched individually along x and y to fill the box.

The default extent is determined by the following conditions.
Pixels have unit size in data coordinates. Their centers are on
integer coordinates, and their center coordinates range from 0 to
columns-1 horizontally and from 0 to rows-1 vertically.

Note that the direction of the vertical axis and thus the default
values for top and bottom depend on origin:

- For origin == 'upper' the default is
(-0.5, numcols-0.5, numrows-0.5, -0.5).
- For origin == 'lower' the default is
(-0.5, numcols-0.5, -0.5, numrows-0.5).

See the :doc:/tutorials/intermediate/imshow_extent tutorial for
examples and a more detailed description.
interpolation_stage NoneType None If ‘data’, interpolation
is carried out on the data provided by the user. If ‘rgba’, the
interpolation is carried out after the colormapping has been
applied (visual interpolation).
filternorm bool True A parameter for the antigrain image resize filter (see the
antigrain documentation). If filternorm is set, the filter
normalizes integer values and corrects the rounding errors. It
doesn’t do anything with the source floating point values, it
corrects only integers according to the rule of 1.0 which means
that any sum of pixel weights must be equal to 1.0. So, the
filter function must produce a graph of the proper shape.
filterrad float 4.0 The filter radius for filters that have a radius parameter, i.e.
when interpolation is one of: ‘sinc’, ‘lanczos’ or ‘blackman’.
resample NoneType None When True, use a full resampling method. When False, only
resample when the output image is larger than the input image.
url NoneType None Set the url of the created .AxesImage. See .Artist.set_url.
data NoneType None
show_images(torch.rand(4,3,28,28), nrows=2, titles=['a','b','c','d'])

Jeremy noticed that there is no fancy init done with the UNet in diffusers. Hence this function, which does some sensible-looking initialization:


source

init_ddpm

 init_ddpm (model)

It’s nice to quickly load images from a URL or file:


source

load_image

 load_image (url, size=None, return_tensor=False)