- Back to Home »
- Numpy <=> Tensor
Posted by : Sushanth
Wednesday, 5 January 2022
Below code snippets helps to convert the numpy to tensor and vice versa
Tensor to Numpy:
x = torch.tensor([[1,2],[3,4],[5,6]])
x_numpy = x.numpy()
print(x_numpy)
print(type(x_numpy))
output:
[[1 2]
[3 4]
[5 6]]
<class 'numpy.ndarray'>
------------------------------------------------------
Numpy to Tensor:
# define numpy array with random values
a = np.random.randn(5)
print(a)
print(type(a))
# convert numpy array to tensor
a_pt = torch.from_numpy(a)
print(type(a_pt))
print(a_pt)
# both reference the same underlying store, updating one will update other one as
# well
output:
[ 0.8716209 -1.92740041 0.83391021 0.30413314 0.01142092]
<class 'numpy.ndarray'>
<class 'torch.Tensor'>
tensor([ 0.8716, -1.9274, 0.8339, 0.3041, 0.0114], dtype=torch.float64)
----------------------------------------------------------------
# update to numpy array updates the Torch.tensor as well if one is created from other
np.add(a,1,out=a) # point wise addition of 1 to all elements of a
print(a)
print(a_pt)
output:
[2.8716209 0.07259959 2.83391021 2.30413314 2.01142092]
tensor([2.8716, 0.0726, 2.8339, 2.3041, 2.0114], dtype=torch.float64)