Convert objects of various python types to :obj:`torch.Tensor`. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int` and :class:`float`. Args: data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to be con
(
data: Union[torch.Tensor, np.ndarray, Sequence, int,
float])
| 14 | |
| 15 | |
| 16 | def to_tensor( |
| 17 | data: Union[torch.Tensor, np.ndarray, Sequence, int, |
| 18 | float]) -> torch.Tensor: |
| 19 | """Convert objects of various python types to :obj:`torch.Tensor`. |
| 20 | |
| 21 | Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, |
| 22 | :class:`Sequence`, :class:`int` and :class:`float`. |
| 23 | |
| 24 | Args: |
| 25 | data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to |
| 26 | be converted. |
| 27 | |
| 28 | Returns: |
| 29 | torch.Tensor: the converted data. |
| 30 | """ |
| 31 | |
| 32 | if isinstance(data, torch.Tensor): |
| 33 | return data |
| 34 | elif isinstance(data, np.ndarray): |
| 35 | if data.dtype is dtype('float64'): |
| 36 | data = data.astype(np.float32) |
| 37 | return torch.from_numpy(data) |
| 38 | elif isinstance(data, Sequence) and not mmengine.is_str(data): |
| 39 | return torch.tensor(data) |
| 40 | elif isinstance(data, int): |
| 41 | return torch.LongTensor([data]) |
| 42 | elif isinstance(data, float): |
| 43 | return torch.FloatTensor([data]) |
| 44 | else: |
| 45 | raise TypeError(f'type {type(data)} cannot be converted to tensor.') |
| 46 | |
| 47 | |
| 48 | @TRANSFORMS.register_module() |