MCPcopy Create free account
hub / github.com/MotrixLab/AiOS / to_tensor

Function to_tensor

util/formatting.py:10–30  ·  view source on GitHub ↗

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`.

(data)

Source from the content-addressed store, hash-verified

8
9
10def to_tensor(data):
11 """Convert objects of various python types to :obj:`torch.Tensor`.
12
13 Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
14 :class:`Sequence`, :class:`int` and :class:`float`.
15 """
16 if isinstance(data, torch.Tensor):
17 return data
18 elif isinstance(data, np.ndarray):
19 return torch.from_numpy(data)
20 elif isinstance(data, Sequence) and not mmcv.is_str(data):
21 return torch.tensor(data)
22 elif isinstance(data, int):
23 return torch.LongTensor([data])
24 elif isinstance(data, float):
25 return torch.FloatTensor([data])
26 else:
27 raise TypeError(
28 f'Type {type(data)} cannot be converted to tensor.'
29 'Supported types are: `numpy.ndarray`, `torch.Tensor`, '
30 '`Sequence`, `int` and `float`')
31
32
33class ToTensor(object):

Callers 3

__call__Method · 0.70
__call__Method · 0.70
__call__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected