utils

Utility functions to make programming easier

Misc


source

get_images

 get_images (path, suffixes=('.jpg', '.jpeg', '.png'))

source

set_seed

 set_seed (seed, deterministic=False)

source

inplace

 inplace (f)

Return the object passed to the function for in place mods


source

mask2idxs

 mask2idxs (mask)
mask = fc.L(True, False, True, False, True)
fc.test_eq(mask2idxs(mask), [0, 2, 4])
fc.test_eq(mask2idxs(~mask), [1,3])

source

PPDict


source

retrieve_global_name

 retrieve_global_name (var)

Memory

Much of this code is taken from the minai library from fastai


source

clean_ipython_hist

 clean_ipython_hist ()

source

clean_traceback

 clean_traceback ()

Objects in tracebacks are stored in memory, even cuda memory. This clears that traceback memory up


source

clean_memory

 clean_memory ()

Cleans all memory from hist and tracebacks

Device Management


source

to_cpu

 to_cpu (x)

source

to_device

 to_device (x:<built-inmethodtensoroftypeobjectat0x7faab94b3460>,
            device='cpu')

MatplotLib Helpers

Much of this code is taken from the minai library from fastai

/opt/hostedtoolcache/Python/3.10.10/x64/lib/python3.10/site-packages/fastcore/docscrape.py:225: UserWarning: Unknown section Other Parameters
  else: warn(msg)
/opt/hostedtoolcache/Python/3.10.10/x64/lib/python3.10/site-packages/fastcore/docscrape.py:225: UserWarning: Unknown section See Also
  else: warn(msg)
/opt/hostedtoolcache/Python/3.10.10/x64/lib/python3.10/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 + Moves to cpu & detach + converts to numpy + remove axis ticks

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

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

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

show_images

 show_images (ims:list, nrows:int|None=None, ncols:int|None=None,
              titles:list|None=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 int | None None Number of rows in grid
ncols int | None None Number of columns in grid (auto-calculated if None)
titles list | None 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

Callbacks


source

run_callbacks

 run_callbacks (callbacks, method_name, trainer=None)

source

add_callbacks

 add_callbacks (trainer, callbacks, force=False)

source

add_callback

 add_callback (trainer, callback, force=False)

source

remove_callbacks

 remove_callbacks (trainer, callbacks, delete=False)

source

remove_callback

 remove_callback (trainer, callback, delete=False)

source

with_cbs

 with_cbs (nm, exception)

Initialize self. See help(type(self)) for accurate signature.

Hooks


source

Hook

 Hook (module, func)

Initialize self. See help(type(self)) for accurate signature.


source

Hooks

 Hooks (modules, func)

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.