(
x: Union[torch.Tensor, np.ndarray, int, float, list, tuple],
accept_none: bool=True, dtype: torch.dtype=None, device='cpu')
| 264 | |
| 265 | |
| 266 | def convert_any_to_torch_tensor( |
| 267 | x: Union[torch.Tensor, np.ndarray, int, float, list, tuple], |
| 268 | accept_none: bool=True, dtype: torch.dtype=None, device='cpu') -> torch.Tensor: |
| 269 | if x is None and accept_none: return None |
| 270 | if x is None and not accept_none: raise ValueError('Trying to convert an empty value.') |
| 271 | if isinstance(x, list) or isinstance(x, tuple): |
| 272 | if all([type(element) == int for element in x]): |
| 273 | if dtype is None: dtype=torch.int64 |
| 274 | return torch.tensor(x, dtype=dtype, device=device) |
| 275 | elif isinstance(x, int): |
| 276 | if dtype is None: dtype=torch.int64 |
| 277 | return torch.tensor(x, dtype=dtype, device=device) |
| 278 | elif isinstance(x, float): |
| 279 | if dtype is None: dtype=torch.float32 |
| 280 | return torch.tensor(x, dtype=dtype, device=device) |
| 281 | elif isinstance(x, torch.Tensor): |
| 282 | if dtype is not None: x = x.type(dtype) |
| 283 | if device is not None: x = x.to(device) |
| 284 | return x |
| 285 | elif isinstance(x, np.ndarray): |
| 286 | if dtype is None: |
| 287 | dtype = DataType.convert_from_numpy(x.dtype) |
| 288 | dtype = DataType.to_torch(dtype) |
| 289 | return torch.tensor(x.copy(), dtype=dtype, device=device) |
| 290 | else: |
| 291 | raise TypeError(f'input value {x}({type(x)}) can not be converted as torch tensor.') |
| 292 | |
| 293 | |
| 294 | def convert_primary_type_to_list( |
no test coverage detected