PyTorch basics

Now that PyTorch has been installed, we can start experimenting with it. We will start with torch and numpy.

From the top menu, create a new notebook and include the following code:

# first basic understanding on PyTorch 
# book: AI for Mobile application projects

import torch
import numpy as np

# convert numpy to tensor or vise versa
numpy_data = np.arange(8).reshape((2, 4))
torch_data = torch.from_numpy(numpy_data)
#convert tensor to array
tensor2array = torch_data.numpy()

#Print the results
print
(
' numpy array:', numpy_data, # [[0 1 2 3], [4 5 6 7]]
' torch tensor:', torch_data, # 0 1 2 3 4 5 6 7 [torch.LongTensor of size 2x3]
' tensor to array:', tensor2array, # [[0 1 2 3], [4 5 6 7]]
)

Now, let's do some mathematical operations:

# abs method on numpy
numpy_data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(numpy_data) # 32-bit floating point

#print the results
print
(
' abs',
' numpy: ', np.abs(numpy_data), # [1 2 1 2]
' torch: ', torch.abs(tensor) # [1 2 1 2]
)

# sin method on numpy
#print the results
print
(
' sin',
' numpy: ', np.sin(numpy_data), # [-0.84147098 -0.90929743 0.84147098 0.90929743]
' torch: ', torch.sin(tensor) # [-0.8415 -0.9093 0.8415 0.9093]
)

Let's calculate the mean method and print the results:


#print the results
print
(
' mean',
' numpy: ', np.mean(data), # 0.0
' torch: ', torch.mean(tensor) # 0.0
)

# matrix multiplication with numpy
numpy_data = [[1,2], [3,4]]
tensor = torch.FloatTensor(numpy_data) # 32-bit floating point
# correct method and print the results
print(
' matrix multiplication (matmul)',
' numpy: ', np.matmul(numpy_data, numpy_data), # [[7, 10], [15, 22]]
' torch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]]
)

The following code shows the output of the mathematical operations:

numpy array: [[0 1 2 3]
 [4 5 6 7]] 
torch tensor: tensor([[0, 1, 2, 3],
        [4, 5, 6, 7]]) 
tensor to array: [[0 1 2 3]
 [4 5 6 7]]

abs 
numpy:  [1 2 1 2] 
torch:  tensor([1., 2., 1., 2.])

sin 
numpy:  [-0.84147098 -0.90929743  0.84147098  0.90929743] 
torch:  tensor([-0.8415, -0.9093,  0.8415,  0.9093])

mean 
numpy:  0.0 
torch:  tensor(0.)

matrix multiplication (matmul) 
numpy:  [[ 7 10]
 [15 22]] 
torch:  tensor([[ 7., 10.],
        [15., 22.]])

Now, let's look at how to use different variables in PyTorch.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset