Convert each element in arr from torch.Tensor to numpy ndarray. Note that the output share the same memory as arr if on cpu.
(
arr: T.Union[np.ndarray, T.List[np.ndarray], T.Dict[str, T.Any]],
dtype: np.dtype = None
)
| 47 | |
| 48 | |
| 49 | def to_numpy( |
| 50 | arr: T.Union[np.ndarray, T.List[np.ndarray], T.Dict[str, T.Any]], |
| 51 | dtype: np.dtype = None |
| 52 | ) -> T.Union[torch.Tensor, T.List[torch.Tensor], T.Dict[str, T.Any]]: |
| 53 | """ |
| 54 | Convert each element in arr from torch.Tensor to numpy ndarray. |
| 55 | Note that the output share the same memory as arr if on cpu. |
| 56 | """ |
| 57 | if isinstance(arr, torch.Tensor): |
| 58 | arr = arr.detach().cpu().numpy() |
| 59 | if dtype is not None: |
| 60 | arr = arr.astype(dtype) |
| 61 | return arr |
| 62 | elif isinstance(arr, np.ndarray) and dtype is not None: |
| 63 | arr = arr.astype(dtype) |
| 64 | return arr |
| 65 | elif isinstance(arr, (list, tuple)): |
| 66 | return [to_numpy(x, dtype=dtype) for x in arr] |
| 67 | elif isinstance(arr, dict): |
| 68 | out_dict = dict() |
| 69 | for key, val in arr.items(): |
| 70 | out_dict[key] = to_numpy(val, dtype=dtype) |
| 71 | return out_dict |
| 72 | else: |
| 73 | return arr |
| 74 | |
| 75 | |
| 76 | def to_device( |