Skip to content

cornucopia.base

Transform

Transform(*, returns=None, append=False, prefix=True, include=None, exclude=None, consume=None)

Bases: Module, ABC

Base class for all transforms.

Parameters:

Name Type Description Default
returns [list or dict of] str

Which tensors to return. Can be a nested structure. Most transforms accept 'input' and 'output' as valid returns. The default is 'output'.

None
append bool

Append the (structure of) returned tensors to the parent structure.

False
prefix bool or str

If append and parent is a dict, prefix the returned key before inserting it in the output dictionary. If True, the prefix is the input key.

True
include str or list[str]

List of keys to which the transform should apply. Default: all.

None
exclude str or list[str]

List of keys to which the transform should not apply. Default: none.

None
consume str or list[str]

List of keys to remove from the output after applying the transform. Default: none.

v0.5 Added in v0.5

None

is_final property

is_final

Whether the transform is final (i.e., deterministic) or not.

get_prm

get_prm()

Get the parameters of the transform, for use in subtransforms.

forward

forward(*a, **k)

Apply the transform recursively.

Parameters:

Name Type Description Default
*a [nested list or dict of] tensor

Input tensors, with shape (C, *shape)

()
**k [nested list or dict of] tensor

Input tensors, with shape (C, *shape)

()

Returns:

Type Description
[nested list or dict of] tensor

Output tensors. with shape (C, *shape)

xform

xform(x, /, args=NoArguments())

Apply the transform to a tensor

Parameters:

Name Type Description Default
x (C_inp, *spatial_inp) tensor

A single input tensor

required
args Arguments

The original inputs arguments to the transform, in case they are needed.

NoArguments()

Returns:

Name Type Description
y Returned | (C_out, *spatial_out) tensor

A single output tensor, or a Returned object containing multiple output tensors and their corresponding keys.

make_final

make_final(x, /, max_depth=inf, args=NoArguments())

Generate a final (i.e., deterministic) version of the transform.

Parameters:

Name Type Description Default
x tensor

A single input tensor, with shape (C, *shape).

required
max_depth int | {inf}

Maximum depth to apply make_final recursively. If not inf, the resulting transform may not be fully final. Default: no limit.

inf
args Arguments

The original inputs arguments to the transform, in case they are needed.

NoArguments()

Returns:

Type Description
Transform

A final version of the transform.

inverse

inverse(*a, **k)

Apply the inverse transform recursively

Parameters:

Name Type Description Default
*a [nested list or dict of] tensor

Input tensors, with shape (C, *shape)

()
**k [nested list or dict of] tensor

Input tensors, with shape (C, *shape)

()

Returns:

Type Description
[nested list or dict of] tensor

Output tensors. with shape (C, *shape)

make_inverse

make_inverse()

Generate the inverse transform

FinalTransform

FinalTransform(*, returns=None, append=False, prefix=True, include=None, exclude=None, consume=None)

Bases: Transform

Base class for determinstic transforms.

Final transforms must implement the xform method.

IdentityTransform

IdentityTransform(*, returns=None, append=False, prefix=True, include=None, exclude=None, consume=None)

Bases: FinalTransform

Identity transform

SharedMixin

Mixin for transforms that have parameters (e.g. random ones) that may be shared across tensors and/or channels or independent across tensors and/or channels.

NonFinalTransform

NonFinalTransform(*, shared=False, **kwargs)

Bases: SharedMixin, Transform

Transforms whose parameters depend on features of the input transform (shape, dtype, etc)

Parameters:

Name Type Description Default
shared (channels, tensors, channels + tensor, '')
  • 'channel': the same transform is applied to all channels in a tensor, but different transforms are used in different tensors.
  • 'tensors': the same transform is applied to all tensors, but with a different transform for each channel.
  • 'channels+tensors' or True: the same transform is applied to all channels of all tensors.
  • '' or False: A different transform is applied to each channel and each tensor.
'channels'

SequentialTransform

SequentialTransform(transforms, **kwargs)

Bases: SharedMixin, Transform

A sequence of transforms

Example

Sequences can be built explicitly, or simply by adding transforms together:

t1 = MultFieldTransform()
t2 = GaussianNoiseTransform()
seq = SequentialTransform([t1, t2])     # explicit
seq = t1 + t2                           # implicit

Sequences can also be extended by addition:

seq += SmoothTransform()

Parameters:

Name Type Description Default
transforms list[Transform]

A list of transforms to apply sequentially.

required

Other Parameters:

Name Type Description
shared (channels, tensors, channels + tensor, '')
  • 'channel': the same sequence is applied to all channels in a tensor, but different transforms are used in different tensors.
  • 'tensors': the same transform is applied to all tensors, but with a different transform for each channel.
  • 'channels+tensors' or True: the same transform is applied to all channels of all tensors.
  • None or False: A different transform is applied to each channel and each tensor.
include str or list[str]

List of keys to which the transform should apply

exclude str or list[str]

List of keys to which the transform should not apply

PerChannelTransform

PerChannelTransform(transforms, **kwargs)

Bases: Transform

Apply a different transform to each channel

Parameters:

Name Type Description Default
transforms list[Transform]

A list of transforms to apply to each channel.

required

MaybeTransform

MaybeTransform(transform, prob=0.5, *, shared=True, **kwargs)

Bases: SharedMixin, Transform

Randomly apply a transform

20% chance of adding noise

import cornucopia as cc
gauss = cc.GaussianNoiseTransform()
Explicit call to the class:
 img = cc.MaybeTransform(gauss, 0.2)(img)
Implicit call using syntactic sugar:
img = (0.2 * gauss)(img)
```

v0.4 Default for shared changed from False to True

Parameters:

Name Type Description Default
transform Transform

A transform to randomly apply

required
prob float

Probability to apply the transform

0.5
shared (channels, tensors, channels + tensor, '')

Roll the dice once for all input tensors

'channels'

SwitchTransform

SwitchTransform(transforms, prob=0, *, shared=True, **kwargs)

Bases: SharedMixin, Transform

Randomly choose a transform to apply

Randomly apply either Gaussian or Chi noise

import cornucopia as cc
gauss = cc.GaussianNoiseTransform()
chi = cc.ChiNoiseTransform()
Explicit call to the class:
img = cc.SwitchTransform([gauss, chi])(img)
Implicit call using syntactic sugar:
img = (gauss | chi)(img)
Functional call:
img = cc.switch({gauss: 0.5, chi: 0.5})(img)

v0.4 Default for shared changed from False to True

Parameters:

Name Type Description Default
transforms list[Transform]

A list of transforms to sample from

required
prob list[float]

Probability of applying each transform

0
shared (channels, tensors, channels + tensor, '')

Roll the dice once for all input tensors

'channels'

IncludeKeysTransform

IncludeKeysTransform(transform, keys, union=True)

Bases: Transform

Context manager for keys to include

Use as a transform

from cornucopia import IncludeKeysTransform
newxform = IncludeKeysTransform(xform, "image)
image, label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import IncludeKeysTransform
with IncludeKeysTransform(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import IncludeKeysTransform
with IncludeKeysTransform(xform, "image"):
    image, label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.include(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Include the union of what was already included and keys

True

ExcludeKeysTransform

ExcludeKeysTransform(transform, keys, union=True)

Bases: Transform

Context manager for keys to exclude. Can also be used as a transform.

Use as a transform

from cornucopia import ExcludeKeysTransform
newxform = ExcludeKeysTransform(xform, "image)
image, label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import ExcludeKeysTransform
with ExcludeKeysTransform(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import ExcludeKeysTransform
with ExcludeKeysTransform(xform, "image"):
    image, label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.exclude(xform, "image") as newxform:
    image, label = newxform(image=image, label=label)

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Exclude the union of what was already excluded and keys

True

ConsumeKeysTransform

ConsumeKeysTransform(transform, keys, union=True)

Bases: Transform

Context manager for keys to consume. Can also be used as a transform.

Use as a transform

from cornucopia import ConsumeKeysTransform
newxform = ConsumeKeysTransform(xform, "image)
label = newxform(image=image, label=label)

Use as a context manager with as

from cornucopia import ConsumeKeysTransform
with ConsumeKeysTransform(xform, "image") as newxform:
    label = newxform(image=image, label=label)

Use as a context manager with

from cornucopia import ConsumeKeysTransform
with ConsumeKeysTransform(xform, "image"):
    label = xform(image=image, label=label)

Use as a context manager (alias)

from cornucopia import ctx
with ctx.consume(xform, "image") as newxform:
    label = newxform(image=image, label=label)

v0.5 Added in v0.5

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
keys [sequence of] str

Keys to include

required
union bool

Consume the union of what was already consumed and keys

True

SharedTransform

SharedTransform(transform, mode=UNSET)

Bases: SharedMixin, Transform

Context manager for sharing transforms across channels / tensors. Can also be used as a transform.

Use as a context manager (alias)

from cornucopia import ctx
with ctx.shared(xform, "channels") as newxform:
    image = newxform(image)

Parameters:

Name Type Description Default
transform Transform

Transform to apply

required
mode (channels, tensors, channels + tensor, '')
  • 'channel': the same transform is applied to all channels in a tensor, but different transforms are used in different tensors.
  • 'tensors': the same transform is applied to all tensors, but with a different transform for each channel.
  • 'channels+tensors' or True: the same transform is applied to all channels of all tensors.
  • None or False: A different transform is applied to each channel and each tensor.
'channels'

ReturningTransform

ReturningTransform(transform, returns=None)

Bases: Transform

Context manager for sharing transforms across channels / tensors

Use as a context manager (alias)

from cornucopia import ctx
with ctx.returns(xform, "channels") as newxform:
    image = newxform(image)

MappedTransform

MappedTransform(*mapargs, nested=False, default=None, **mapkwargs)

Bases: Transform

Transforms that are applied to specific positional or arguments

Example

img = torch.randn([1, 32, 32])
seg = torch.randn([3, 32, 32]).softmax(0)

# positional variant
trf = MappedTransform(GaussianNoise(), None)
img, seg = trf(img, seg)

# keyword variant
trf = MappedTransform(image=GaussianNoise())
img, seg = trf(image=img, label=seg)

# alternative version
dat = {'img': torch.randn([1, 32, 32]),
       'seg': torch.randn([3, 32, 32]).softmax(0)}
dat = MappedTransform(img=GaussianNoise(), nested=True)(dat)

Parameters:

Name Type Description Default
mapargs tuple[Transform]

Transform to apply to positional arguments

()
mapkwargs dict[str, Transform]

Transform to apply to keyword arguments

{}
nested bool

Recursively traverse the inputs until we find matching dictionaries. Only mapkwargs are accepted if "nested".

False
default Transform

Transform to apply if nothing is specifically mapped

None

RandomizedTransform

RandomizedTransform(transform, sample=tuple(), ksample=dict(), *, shared=False, **kwargs)

Bases: NonFinalTransform

Transform generated by randomizing some parameters of another transform.

ctx.randomize is an alias for RandomizedTransform

Gaussian noise with randomized variance

Object call

import cornucopia as cc
hypernoise = cc.RandomizedTransform(cc.GaussianNoise, [cc.Uniform()])
img = hypernoise(img)

Delayed call

import cornucopia as cc
MyRandomNoise = cc.randomize(cc.GaussianNoise)
hypernoise = MyRandomNoise(cc.Uniform())
img = hypernoise(img)

Parameters:

Name Type Description Default
transform callable(...) -> Transform

A Transform subclass or a function that constructs a Transform.

required
sample [list or dict of] callable

A collection of functions that generate parameter values provided to transform. Can be args-like or kwargs-like arguments.

tuple()
ksample dict[callable]

Must be kwargs-like arguments.

dict()

Other Parameters:

Name Type Description
shared (channels, tensors, channels + tensors, '')

Share random parameters across tensors and/or channels