Python beginners touch Pytorch (1)

Nice to meet you, my name is Yusaku Sekine. This is my first article, so I'm nervous, but I'll do my best to write it, so please contact me if you have any suggestions. Also, in this article, I will omit the explanation of how to install Pytorch and the basic grammar. It focuses on the basic grammar of Pytorch.

1. Background of writing the article

I'm interested in artificial intelligence and have been using TensorFlow </ strong> for a long time, but now I can't use TensorFlow on my Windows device. Therefore, I decided to take this opportunity to switch to Pytorch </ strong> and write an article as a practice.
The learning method is as follows.

  1. Official document Pytorch tutrial link
  2. Net article (Qitta or technical blog)
  3. Actually move This article is based on the official document, so if you want to read it in the original text, please see the official document.

2. Introduction to Pytorch

2-1. Tensor First of all, the basic data form Tensor of Pytorch to be used. Create and run the following code. This article does not go into deep detail about what a Tensor is. For the time being, I think you should think of it as something similar to a procession.

torch1.py


import torch
tensor = torch.rand(3,3)
print(tensor)

result


tensor([[0.7545, 0.3774, 0.7312],
        [0.9000, 0.6083, 0.5135],
        [0.6012, 0.9147, 0.0625]]

The word "tensor" is written in the execution result. pytorch calculates this tensor and performs machine learning. Also, torch.rand randomly generates numbers from 0 to 1 (rows, columns). You may find it even better if you run it with different row and column numbers.
Next, let's declare a general tensor.

torch2.py


import torch
tensor = torch.tensor([[1,2,3],
                      [4,5,6],
                      [7,8,9]])
print(tensor)

result


tensor([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])

You can also declare a tensor here. Select the tensor generation method according to the usage.

2-2. Basic calculation of Tensor Now that you can declare a tensor, let's do a calculation using this tensor. Since it's a big deal, let's find the sum, difference, product, and quotient using the tensor declared earlier.

torch2.py


import torch
tensor = torch.tensor([[1,2,3],
                      [4,5,6],
                      [7,8,9]])

print("sum")
print(tensor+tensor)
print("difference")
print(tensor-tensor)
print("product")
print(tensor*tensor)
print("quotient")
print(tensor//tensor)

result


sum
tensor([[ 2,  4,  6],
        [ 8, 10, 12],
        [14, 16, 18]])
difference
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
product
tensor([[ 1,  4,  9],
        [16, 25, 36],
        [49, 64, 81]])
quotient
tensor([[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]])

You can confirm that the calculation is completed without any problem.

As an aside, the sum and difference between tensors can be calculated in other ways.

tensor3.py


import torch
print(torch.add(tensor,tensor))
print(torch.sub(tensor,tensor))

result


tensor([[ 2,  4,  6],
        [ 8, 10, 12],
        [14, 16, 18]])

tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

2-3. Convenient calculation function Here are some of the features I found useful while using Pytorch. It's just my feeling, so it may be fun to search for useful functions by yourself. * All can be used after performing "import torch".

2-3-1. Generate an arbitrary number 0 or 1

zeros_and_ones.py


print(torch.zeros(3,3))
print(torch.ones(3,3))

result


tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])

tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])

2-3-2. Maximum and minimum values

max_and_min.py


tensor = torch.tensor([[1,2,3],
                       [4,5,6],
                       [7,8,9]])
print(torch.max(tensor))
print(torch.min(tensor))

result


tensor(9)
tensor(1)

2-3-3.Tensor size check

tensor_size.py


tensor = torch.tensor([[1,2,3],
                       [4,5,6],
                       [7,8,9]])
print(tensor.size())

result


torch.Size([3, 3])

2-3-4. Sum of all elements in Tensor

sum_of_tensor.py


tensor = torch.tensor([1,2,3,4,5])

print(torch.sum(tensor))
tensor(15)

2-3-5. Rounding of Tensor, calculation of absolute value

round_abs.py


#Absolute value tensor
tensor1 = torch.tensor([[-1,-2,-3],
                        [-4,-5,-6],
                        [-7,-8,-9]])

#Rounding tensor
tensor2 = torch.tensor([[1.1,2.4,3.5],
                        [-4.5,-5.7,-6.8],
                        [-7.1,-8.1,-9.0]])

print(torch.abs(tensor1))
print(torch.round(tensor2))

result


tensor([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])

tensor([[ 1.,  2.,  4.],
        [-4., -6., -7.],
        [-7., -8., -9.]])
  • If the number is negative, it may be devalued at 5. I have a devaluation.

2-3-6.Tensor factorial, square root calculation

pow_sqrt.py


#Factorial calculation tensor
tensor3 = torch.tensor([[1,2,3],
                        [4,5,6],
                        [7,8,9]])
'''
Square root calculation tensor
If you want to do a square root, you need to change the type to float. Type conversion is dtype= "Mold"
'''
tensor4 = torch.tensor([[1,4,9],
                        [16,25,36],
                        [49,64,81]],dtype=torch.float32)

print(torch.pow(tensor3,2)) #It can be multiplied by changing the part 2 arbitrarily.
print(torch.sqrt(tensor4))

result


tensor([[ 1,  4,  9],
        [16, 25, 36],
        [49, 64, 81]])

tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]])

2-3-7.tensor conversion from numpy to The well-known extension module'numpy' Pytorch used in Python's matrix computation can also convert numpy to a tensor.

numpy_to_tensor.py


import numpy as np
import torch

numpy = np.array([1,2,3,4,5])
numpy_to_tensor = torch.from_numpy(numpy)
print(numpy)
print(numpy_to_tensor)

result


[1 2 3 4 5]
tensor([1, 2, 3, 4, 5])
#It can be confirmed that the notation is different between "numpy" and "tensor".

Finally This time, I introduced a simple tensor and tensor calculation. Next, I will write an article on differentiation with some mathematical elements. I would like to improve Qitta's article writing ability, so please point out any suggestions or improvements.

Thank you for reading until the end.

Recommended Posts