LabelTensor#

class LabelTensor(x, labels, *args, **kwargs)[source]#

Bases: Tensor

Extension of the torch.Tensor class that includes labels for each dimension.

Initialize the LabelTensor instance, by checking the consistency of the labels and the tensor. Specifically, the labels must match the following conditions:

  • At each dimension, the number of labels must match the size of the dimension.

  • At each dimension, the labels must be unique.

The labels can be passed in the following formats:

Example:
>>> from pina import LabelTensor
>>> tensor = LabelTensor(
>>>     torch.rand((2000, 3)),
...     {1: {"name": "space", "dof": ['a', 'b', 'c'])
>>> tensor = LabelTensor(
>>>     torch.rand((2000, 3)),
...     ["a", "b", "c"])

The keys of the dictionary are the dimension indices, and the values are dictionaries containing the labels and the name of the dimension. If the labels are passed as a list, these are assigned to the last dimension.

Parameters:
Raises:

ValueError – If the labels are not consistent with the tensor.

property tensor#

Returns the tensor part of the LabelTensor object.

Returns:

Tensor part of the LabelTensor.

Return type:

torch.Tensor

property full_labels#

Returns the full labels of the tensor, even for the dimensions that are not labeled.

Returns:

The full labels of the tensor

Return type:

dict

property stored_labels#

Returns the labels stored inside the instance.

Returns:

The labels stored inside the instance.

Return type:

dict

property labels#

Returns the labels of the last dimension of the instance.

Returns:

labels of last dimension

Return type:

list

_init_labels_from_dict(labels)[source]#

Store the internal label representation according to the values passed as input.

Parameters:

labels (dict) – The label(s) to update.

Raises:

ValueError – If the dof list contains duplicates or the number of dof does not match the tensor shape.

_init_labels_from_list(labels)[source]#

Given a list of dof, this method update the internal label representation by assigning the dof to the last dimension.

Parameters:

labels (list) – The label(s) to update.

extract(labels_to_extract)[source]#

Extract the subset of the original tensor by returning all the positions corresponding to the passed label_to_extract. If label_to_extract is a dictionary, the keys are the dimension names and the values are the labels to extract. If a single label or a list of labels is passed, the last dimension is considered.

Example:
>>> from pina import LabelTensor
>>> labels = {1: {'dof': ["a", "b", "c"], 'name': 'space'}}
>>> tensor = LabelTensor(torch.rand((2000, 3)), labels)
>>> tensor.extract("a")
>>> tensor.extract(["a", "b"])
>>> tensor.extract({"space": ["a", "b"]})
Parameters:

labels_to_extract (str | list[str] | tuple[str] | dict) – The label(s) to extract.

Returns:

The extracted tensor with the updated labels.

Return type:

LabelTensor

Raises:
  • TypeError – Labels are not str, list[str] or dict properly setted.

  • ValueError – Label to extract is not in the labels list.

static cat(tensors, dim=0)[source]#

Concatenate a list of tensors along a specified dimension. For more details, see torch.cat().

Parameters:
  • tensors (list[LabelTensor]) – LabelTensor instances to concatenate

  • dim (int) – Dimensions on which you want to perform the operation (default is 0)

Returns:

A new LabelTensor instance obtained by concatenating the input instances.

Return type:

LabelTensor

Raises:

ValueError – either number dof or dimensions names differ.

static stack(tensors)[source]#

Stacks a list of tensors along a new dimension. For more details, see torch.stack().

Parameters:

tensors (list[LabelTensor]) – A list of tensors to stack. All tensors must have the same shape.

Returns:

A new LabelTensor instance obtained by stacking the input tensors.

Return type:

LabelTensor

requires_grad_(mode=True)[source]#

Override the requires_grad_() method to handle the labels in the new tensor. For more details, see requires_grad_().

Parameters:

mode (bool) – A boolean value indicating whether the tensor should track gradients.If True, the tensor will track gradients; if False, it will not.

Returns:

The LabelTensor itself with the updated requires_grad state and retained labels.

Return type:

LabelTensor

property dtype#

Give the dtype of the tensor. For more details, see torch.dtype().

Returns:

The data type of the tensor.

Return type:

torch.dtype

to(*args, **kwargs)[source]#

Performs Tensor dtype and/or device conversion. For more details, see torch.Tensor.to().

Returns:

A new LabelTensor instance with the updated dtype and/or device and retained labels.

Return type:

LabelTensor

clone(*args, **kwargs)[source]#

Clone the LabelTensor. For more details, see torch.Tensor.clone().

Returns:

A new LabelTensor instance with the same data and labels but allocated in a different memory location.

Return type:

LabelTensor

append(tensor, mode='std')[source]#

Appends a given tensor to the current tensor along the last dimension. This method supports two types of appending operations:

  1. Standard append (“std”): Concatenates the input tensor with the current tensor along the last dimension.

  2. Cross append (“cross”): Creates a cross-product of the current tensor and the input tensor.

Parameters:
  • tensor (LabelTensor) – The tensor to append to the current tensor.

  • mode (str, optional) – The append mode to use. Defaults to st.

Returns:

A new LabelTensor instance obtained by appending the input tensor.

Return type:

LabelTensor

Raises:

ValueError – If the mode is not “std” or “cross”.

static vstack(tensors)[source]#

Stack tensors vertically. For more details, see torch.vstack().

Parameters:

label_tensors (list of LabelTensor) – The LabelTensor instances to stack. They need to have equal labels.

Returns:

A new LabelTensor instance obtained by stacking the input tensors vertically.

Return type:

LabelTensor

_update_single_label(old_labels, to_update_labels, index, dim, to_update_dim)[source]#

Update the labels of the tensor based on the index (or list of indices).

Parameters:
Raises:

ValueError: If the index type is not supported.

sort_labels(dim=None)[source]#

Sort the labels along the specified dimension and apply. It applies the same sorting to the tensor part of the instance.

Parameters:

dim (int) – The dimension along which to sort the labels. If None, the last dimension is used.

Returns:

A new tensor with sorted labels along the specified dimension.

Return type:

LabelTensor

permute(*dims)[source]#

Permutes the dimensions of the tensor and the associated labels accordingly. For more details, see torch.Tensor.permute().

Parameters:

dims (tuple[int] | list[int]) – The dimensions to permute the tensor to.

Returns:

A new object with permuted dimensions and reordered labels.

Return type:

LabelTensor

detach()[source]#

Detaches the tensor from the computation graph and retains the stored labels. For more details, see torch.Tensor.detach().

Returns:

A new tensor detached from the computation graph.

Return type:

LabelTensor

static summation(tensors)[source]#

Computes the summation of a list of LabelTensor instances.

Parameters:

tensors (list[LabelTensor]) – A list of tensors to sum. All tensors must have the same shape and labels.

Returns:

A new LabelTensor containing the element-wise sum of the input tensors.

Return type:

LabelTensor

Raises:
  • ValueError – If the input tensors list is empty.

  • RuntimeError – If the tensors have different shapes and/or mismatched labels.

reshape(*shape)[source]#

Override the reshape method to update the labels of the tensor. For more details, see torch.Tensor.reshape().

Parameters:

shape (tuple of int) – The new shape of the tensor.

Returns:

A new LabelTensor instance with the updated shape and labels.

Return type:

LabelTensor