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

Function to_tensor

plib/utils.py:22–46  ·  view source on GitHub ↗

Convert each element in arr from np.ndarray to torch.Tensor. Note that the output share the same memory as arr.

(
        arr: T.Union[np.ndarray, T.List[np.ndarray], T.Dict[str, T.Any]],
        dtype: torch.dtype = None,
)

Source from the content-addressed store, hash-verified

20
21
22def to_tensor(
23 arr: T.Union[np.ndarray, T.List[np.ndarray], T.Dict[str, T.Any]],
24 dtype: torch.dtype = None,
25) -> T.Union[torch.Tensor, T.List[torch.Tensor], T.Dict[str, T.Any]]:
26 """
27 Convert each element in arr from np.ndarray to torch.Tensor.
28 Note that the output share the same memory as arr.
29 """
30 if isinstance(arr, np.ndarray):
31 arr = torch.from_numpy(arr)
32 if dtype is not None:
33 arr = arr.to(dtype=dtype)
34 return arr
35 elif isinstance(arr, torch.Tensor) and dtype is not None:
36 arr = arr.to(dtype=dtype)
37 return arr
38 elif isinstance(arr, (list, tuple)):
39 return [to_tensor(x, dtype=dtype) for x in arr]
40 elif isinstance(arr, dict):
41 out_dict = dict()
42 for key, val in arr.items():
43 out_dict[key] = to_tensor(val, dtype=dtype)
44 return out_dict
45 else:
46 return arr
47
48
49def to_numpy(

Callers

nothing calls this directly

Calls 1

toMethod · 0.45

Tested by

no test coverage detected