1 Creating a matrix with numpy vs pytorch¶
In [2]:
arr = [[1,2], [2,3]]
In [3]:
np.array(arr)
Out[3]:
In [4]:
torch.Tensor(arr)
Out[4]:
In [7]:
np.ones((2,2))
Out[7]:
In [8]:
torch.ones((2,2))
Out[8]:
In [9]:
np.zeros((2,3))
Out[9]:
In [10]:
torch.zeros((2,3))
Out[10]:
2 Random numbers¶
In [11]:
np.random.rand(2,3)
Out[11]:
In [12]:
torch.rand(2,3)
Out[12]:
3 Seed for reproducibility¶
In [15]:
np.random.seed(8)
np.random.randn(2,2)
Out[15]:
In [16]:
np.random.seed(8)
np.random.randn(2,2)
Out[16]:
In [17]:
np.random.randn(2,2)
Out[17]:
In [18]:
torch.manual_seed(8)
torch.randn(2,2)
Out[18]:
In [19]:
torch.manual_seed(8)
torch.randn(2,2)
Out[19]:
In [20]:
torch.randn(2,2)
Out[20]:
4 from_numpy()¶
In [22]:
numpy_arr = np.array(np.random.rand(2,2))
numpy_arr
Out[22]:
In [23]:
type(numpy_arr)
Out[23]:
In [25]:
pytorch_arr = torch.from_numpy(numpy_arr)
pytorch_arr
Out[25]:
In [26]:
type(pytorch_arr)
Out[26]:
How to change the datatype to IntTensor?¶
In [32]:
numpy_arr = np.array(np.random.rand(2,2), dtype=np.int32)
numpy_arr
Out[32]:
In [33]:
type(numpy_arr)
Out[33]:
In [34]:
pytorch_arr = torch.from_numpy(numpy_arr)
pytorch_arr
Out[34]:
In [35]:
type(pytorch_arr)
Out[35]:
We can convert any numpy array to pytorch tensors using $\verb|torch.from_numpy()|$
How to convert torch tensors to numpy array?¶
In [37]:
torch_tensors = torch.randn(2,2)
torch_tensors
Out[37]:
In [38]:
numpy_arr = torch_tensors.numpy()
numpy_arr
Out[38]:
5. Tensor Operations¶
How to resize torch tensors?¶
Numpy¶
In [43]:
numpy_arr = np.zeros((2,2))
numpy_arr
Out[43]:
In [45]:
numpy_arr.reshape(1,4)
Out[45]:
PyTorch¶
In [46]:
torch_ten = torch.zeros((2,2))
torch_ten
Out[46]:
In [47]:
torch_ten.view(1,4)
Out[47]:
In [48]:
numpy_arr.shape
Out[48]:
In [51]:
torch_ten.size()
Out[51]:
How to do element-wise addition?¶
Numpy¶
In [70]:
a = np.array([[1,2], [2,3]])
a
Out[70]:
In [71]:
b = np.array([[1,2], [2,3]])
b
Out[71]:
In [72]:
a+b
Out[72]:
In [73]:
np.add(a,b)
Out[73]:
PyTorch¶
In [74]:
a = torch.Tensor([[1,2], [2,3]])
a
Out[74]:
In [75]:
b = torch.Tensor([[1,2], [2,3]])
b
Out[75]:
In [76]:
a+b
Out[76]:
In [77]:
torch.add(a,b)
Out[77]:
How to perform inplace additions?¶
PyTorch¶
In [104]:
a = torch.Tensor([[1,2], [2,3]])
a
Out[104]:
In [105]:
b = torch.Tensor([[1,2], [2,3]])
b
Out[105]:
In [106]:
a.add(b) # not in place
Out[106]:
In [107]:
a
Out[107]:
In [108]:
a.add_(b) # in plcace
Out[108]:
In [109]:
a
Out[109]:
In [110]:
np.multiply(a,b)
Out[110]:
In [111]:
torch.mul(a,b)
Out[111]:
In [112]:
a.mul(b)
Out[112]:
How to perform mean operation?¶
In [118]:
numpy_arr = np.array([[1,2,3,4,5], [1,2,3,4,9]])
numpy_arr
Out[118]:
In [119]:
numpy_arr.mean()
Out[119]:
In [120]:
numpy_arr.mean(axis=1)
Out[120]:
In [122]:
torch_ten = torch.Tensor([[1,2,3,4,5],[1,2,3,4,9]])
torch_ten
Out[122]:
In [123]:
torch_ten.mean()
Out[123]:
In [126]:
torch_ten.mean(dim=1)
Out[126]:
In [127]:
numpy_arr.shape
Out[127]:
In [128]:
torch_ten.size()
Out[128]:
No comments :
Post a Comment