ToTensor#

class ToTensor[source]#

Bases: object

Recursively convert numpy arrays and numeric leaves to torch tensors.

Walks the input (which may be the whole data_dict, a nested mapping, or a sequence) and converts supported leaves to torch tensors: int becomes a LongTensor, float becomes a FloatTensor, boolean arrays are kept boolean, integer arrays become long, and floating arrays become float. Existing tensors and strings pass through unchanged; mappings and sequences are rebuilt with each element converted. Place near the end of a pipeline, after the numpy-based geometry and filtering steps but before Collect. Raises TypeError on an unsupported leaf type. Registered as ToTensor – use this string as the type in a transform=[...] config list.

Note

Takes no constructor arguments. Strings are detected before the generic sequence branch so they are left intact rather than split into characters.

Example

>>> import numpy as np
>>> from pimm.datasets.transform import ToTensor
>>> data = {"coord": np.array([[1., 2., 3.]], dtype="f4"),
...         "segment": np.array([2, 3]), "name": "evt0"}
>>> out = ToTensor()(data)
>>> type(out["coord"]).__name__, out["coord"].dtype  # float array -> float tensor
('Tensor', torch.float32)
>>> type(out["segment"]).__name__, out["segment"].dtype  # int array -> long tensor
('Tensor', torch.int64)
>>> out["name"]  # strings pass through unchanged
'evt0'