Pytorch basics-data types

Basic data type

Pytorch provides two types of data abstractions, called tensors and variables. Tensors are similar to arrays in numpu and can also be used on GPUs and can improve performance. In PyTorch, data abstraction provides a simple switch between GPU and CPU.

1. Scalar (0-dimensional tensor)

A tensor containing one element is called a scalar. The definition is as follows:

a = torch.tensor(2.3)
类型进行检查
a.size() #对类型进行检查
Output:torch.Size([])
a.shape  #Type check
Output:torch.Size([])

2. Vector (1-dimensional tensor)

A vector is an array of a sequence of elements. The definition is as follows:

b = torch.tensor([1,2])
c= torch.FloatTensor([1,3,5,8])
print(b)
print(c)
Output:tensor([1, 2])
		tensor([1., 3., 5., 8.])
data = np.ones(2)
torch.from_numpy(data) #从Numpy引入
Output:
tensor([1., 1.], dtype=torch.float64)

3. Matrix (2-dimensional vector)

Most structured data can be represented as tables or matrices. The definition is as follows:

d = torch.FloatTensor([[1,2,3],
                       [4,5,6]])
print(d)
Output:
tensor([[1., 2., 3.],
        [4., 5., 6.]])
#Type check
d.size()
d.shape
Output:
	torch.Size([2, 3])

4. Three-dimensional vector

When multiple matrices are added together, a three-dimensional tensor is obtained, which can be used to represent data like images.

e = torch.FloatTensor([[[1,2,3],
                       [4,5,6]]])
print(e)
Output:
tensor([[[1., 2., 3.],
         [4., 5., 6.]]])
	

5. Four-dimensional vector

A common example of a 4-dimensional tensor type is batch images.

f = torch.rand(1,3,28,28)

Other operations

f.numel represents the amount of memory occupied by Tensor——Number of Element
f.dim() View dimension
f = f.cuda() CPU GPU data conversion

To be improved. . . .

Guess you like

Origin blog.csdn.net/weixin_45680994/article/details/108549353
Recommended