. Pytorch Basics
[1]:
1
print("hello")stdout
hello
[2]:
1
import torch[3]:
1
import numpy as np[4]:
1
torch.__version__Out[4]:
'2.10.0'
[5]:
12
arr=np.array([1,2,3,4,5])
print(arr)stdout
[1 2 3 4 5]
[6]:
1
type(arr)Out[6]:
numpy.ndarray
[8]:
12
# convert to pytorch array
x=torch.from_numpy(arr)Out[8]:
tensor([1, 2, 3, 4, 5])
[9]:
12
# secondoption to convert to tensor
x=torch.as_tensor(arr)Out[9]:
tensor([1, 2, 3, 4, 5])
[10]:
123
# lets create a 2d array
arr2d=np.arange(0.0,12)
arr2dOut[10]:
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.])
[13]:
12
# lets reshape it
arr2d=arr2d.reshape(4,3)[15]:
123
# convert this to tensor
x2=torch.from_numpy(arr2d) # observe this is a 64 bit array
x2Out[15]:
tensor([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9., 10., 11.]], dtype=torch.float64)
[16]:
12345
# link between numpy array and tensor
# if we create a numpy array using below command
arr=np.array([1,2,3,4,5])
x=torch.from_numpy(arr)
arr[0]=99[17]:
1
print(x) # first element will change herestdout
tensor([99, 2, 3, 4, 5])
[19]:
12345
# but if we use torch.tensor it will be a different array
arr=np.array([1,2,3,4,5])
my_tensor=torch.tensor(arr)
my_other_tensor=torch.from_numpy(arr)
my_tensorOut[19]:
tensor([1, 2, 3, 4, 5])
[20]:
1
print(my_other_tensor)stdout
tensor([1, 2, 3, 4, 5])
[21]:
1
arr[0]=99[22]:
1
print(my_tensor) # this will not be effectedstdout
tensor([1, 2, 3, 4, 5])
[23]:
1
print(my_other_tensor) # this will be effected stdout
tensor([99, 2, 3, 4, 5])
[ ]:
1
Previous
Start of course
Next
. Pytorch Basics 2