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