MCPcopy Create free account
hub / github.com/apple/ml-pointersect / to_numpy

Function to_numpy

plib/utils.py:49–73  ·  view source on GitHub ↗

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
)

Source from the content-addressed store, hash-verified

47
48
49def 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
76def to_device(

Callers

nothing calls this directly

Calls 1

detachMethod · 0.45

Tested by

no test coverage detected