The use of Pytorch-Tensor (detailed introduction to basic functions)

1. Introduction to tensor

Pytorch最基本的操作对象是Tensor(张量),它表示一个多维矩阵,张量类似于NumPyndarrays,
张量可以在GPU上使用以加速计算。Tensor可以跟踪计算图和计算梯度。Numpy的计算无法像Tensor一样在GPU上加速。
张量表示由一个数值组成的数组,这个数组可能有多个维度。 具有一个轴的张量对应数学上的向量(vector); 具有两个轴的张量对应数学上的矩阵(matrix); 具有两个轴以上的张量没有特殊的数学名称。

2. Basic usage

2.1 Guide package

import torch

2.2 Getting Started

First, we can use arange to create a row vector x. This row vector contains the first 12 integers starting with 0, which are created as integers by default. You can also specify the creation type as a floating point number. Each value in a tensor is called an element of the tensor. For example, there are 12 elements in the tensor x. Unless otherwise specified, new tensors will be stored in memory and computed on a CPU basis.

x = torch.arange(12)
print(x)

insert image description here
Some common functions (print code not shown)

x = torch.arange(12) #生成0开始的前12个整数
shape = x.shape #访问张量(沿每个轴的长度)的形状
numel = x.numel() #如果只想知道张量中元素的总数,即形状的所有元素乘积,可以检查它的大小(size)
X = x.reshape(-1, 4) #改变形状,-1代表自动匹配 即3*4
zero = torch.zeros((2, 3, 4)) #2组3*4的0矩阵
one = torch.ones(2, 5) #1矩阵
random = torch.randn(3, 4) #随机
xx = torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) 

Result display

insert image description here

2.3 Operators

Common standard arithmetic operators (+, -, *, /, and **) can be upgraded to element-wise operations on arbitrary tensors of the same shape.

x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])

print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x ** y) # **运算符是求幂运算

exp = torch.exp(x) #e的多少次方
print(exp)

insert image description here

2.4 Indexing and Slicing

next time at school

2.5 Broadcast mechanism

In some cases, even if the shapes are different, we can still perform element-wise operations by calling the broadcasting mechanism. This mechanism works as follows: first, one or both arrays are extended by duplicating elements appropriately so that after the transformation, the two tensors have the same shape. Second, perform an element-wise operation on the resulting array.

a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
ab = a + b

print(a)
print(b)
print(ab)

In most cases, we will broadcast
the computation along an axis of length 1 in the array:
insert image description here

result:

insert image description here
Special case:
if it is multiplication here, it is corresponding multiplication, not matrix multiplication

import torch

a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
ab = a * b

print(a)
print(b)
print(ab)

process:
insert image description here

result:
insert image description here

Guess you like

Origin blog.csdn.net/qq_43471945/article/details/127614436