10 examples of 'numpy array to torch tensor' in Python

Every line of 'numpy array to torch tensor' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
32def to_torch(array):
33 if len(array.shape) == 4:
34 array = np.transpose(array, (0, 3, 1, 2))
35 return torch.from_numpy(array).to(device).float()
26def torch2numpy(X):
27 """Convert a torch float32 tensor to a numpy array, sharing the same memory.
28 """
29 return X.detach().numpy()
396def tensor_to_ndarray(tensor):
397 """
398 Convert float tensor into numpy image
399
400 :param tensor: input tensor
401 :type tensor: torch.Tensor
402 :return: numpy image
403 :rtype: np.ndarray
404 """
405 tensor_np = tensor.permute(1, 2, 0).cpu().numpy()
406 tensor_np = tensor_np.astype(np.float32)
407 tensor_np = (tensor_np * 255).astype(np.uint8)
408 return tensor_np
142@staticmethod
143def videos_to_numpy(tensor):
144 generated = tensor.transpose(0, 1, 2, 3, 4)
145 generated[generated < -1] = -1
146 generated[generated > 1] = 1
147 generated = (generated + 1) / 2 * 255
148 return generated.astype('uint8')
20def to_torch(ndarray):
21 if type(ndarray).__module__ == 'numpy':
22 return torch.from_numpy(ndarray)
23 elif not torch.is_tensor(ndarray):
24 raise ValueError("Cannot convert {} to torch tensor".format(type(ndarray)))
25 return ndarray
46def to_tensor(x, cuda=False):
47 if x.ndim == 4:
48 x = x.transpose([0, 3, 1, 2]) / 255.0
49 elif x.ndim == 5:
50 x = x.transpose([0, 1, 4, 2, 3]) / 255.0
51 else:
52 raise ValueError(f"Tensor dimension error: {x.dim()} != 4 or 5")
53 x = torch.as_tensor(x, dtype=torch.float32)
54 if cuda and torch.cuda.is_available():
55 x = x.cuda()
56 return x
36def to_torch(nparray):
37 tensor = torch.from_numpy(nparray).float().cuda()
38 return torch.autograd.Variable(tensor, requires_grad=False)
29@staticmethod
30def to_numpy(tensor):
31 if isinstance(tensor, cp.ndarray):
32 return cp.asnumpy(tensor)
33 return tensor
119def array(self, arr, dtype=None):
120 """ make an array """
121 if dtype is None:
122 dtype = torch.get_default_dtype()
123 return torch.tensor(arr, device="cpu", dtype=dtype)
50def _tensor_to_cuda(x):
51 if x.is_cuda:
52 return x
53 else:
54 return x.cuda()

Related snippets