Convert torch tensor to numpy.ndarray. Args: x (Tensor | Sequence[Tensor]): A single tensor or a sequence of tensors return_device (bool): Whether return the tensor device. Defaults to ``False`` unzip (bool): Whether unzip the input sequence. Defa
(x: Union[Tensor, Sequence[Tensor]],
return_device: bool = False,
unzip: bool = False)
| 9 | |
| 10 | |
| 11 | def to_numpy(x: Union[Tensor, Sequence[Tensor]], |
| 12 | return_device: bool = False, |
| 13 | unzip: bool = False) -> Union[np.ndarray, tuple]: |
| 14 | """Convert torch tensor to numpy.ndarray. |
| 15 | |
| 16 | Args: |
| 17 | x (Tensor | Sequence[Tensor]): A single tensor or a sequence of |
| 18 | tensors |
| 19 | return_device (bool): Whether return the tensor device. Defaults to |
| 20 | ``False`` |
| 21 | unzip (bool): Whether unzip the input sequence. Defaults to ``False`` |
| 22 | |
| 23 | Returns: |
| 24 | np.ndarray | tuple: If ``return_device`` is ``True``, return a tuple |
| 25 | of converted numpy array(s) and the device indicator; otherwise only |
| 26 | return the numpy array(s) |
| 27 | """ |
| 28 | |
| 29 | if isinstance(x, Tensor): |
| 30 | arrays = x.detach().cpu().numpy() |
| 31 | device = x.device |
| 32 | elif isinstance(x, np.ndarray) or is_seq_of(x, np.ndarray): |
| 33 | arrays = x |
| 34 | device = 'cpu' |
| 35 | elif is_seq_of(x, Tensor): |
| 36 | if unzip: |
| 37 | # convert (A, B) -> [(A[0], B[0]), (A[1], B[1]), ...] |
| 38 | arrays = [ |
| 39 | tuple(to_numpy(_x[None, :]) for _x in _each) |
| 40 | for _each in zip(*x) |
| 41 | ] |
| 42 | else: |
| 43 | arrays = [to_numpy(_x) for _x in x] |
| 44 | |
| 45 | device = x[0].device |
| 46 | |
| 47 | else: |
| 48 | raise ValueError(f'Invalid input type {type(x)}') |
| 49 | |
| 50 | if return_device: |
| 51 | return arrays, device |
| 52 | else: |
| 53 | return arrays |
| 54 | |
| 55 | |
| 56 | def to_tensor(x: Union[np.ndarray, Sequence[np.ndarray]], |