dgl.apply_each

dgl.apply_each(data, fn, *args, **kwargs)[source]

Apply a function to every element in a container.

If the input data is a list or any sequence other than a string, returns a list whose elements are the same elements applied with the given function.

If the input data is a dict or any mapping, returns a dict whose keys are the same and values are the elements applied with the given function.

The first argument of the function will be passed with the individual elements from the input data, followed by the arguments in args and kwargs.

Parameters
  • data (any) – Any object.

  • fn (callable) – Any function.

  • args – Additional arguments and keyword-arguments passed to the function.

  • kwargs – Additional arguments and keyword-arguments passed to the function.

Examples

Applying a ReLU function to a dictionary of tensors:

>>> h = {k: torch.randn(3) for k in ['A', 'B', 'C']}
>>> h = apply_each(h, torch.nn.functional.relu)
>>> assert all((v >= 0).all() for v in h.values())