PyTorch入门
本教程旨在使您熟悉PyTorch中的张量的概念,并向您介绍PyTorch中涉及张量的操作。
Pytorch模块使用称为张量的数据结构,与Tensorflow的数据结构非常相似。
但是,Pytorch不需要先验地定义整个计算图。
这使得Pytorch易于调试和理解。
Pytorch中的张量
张量是类似于NumPy模块中出现的多维结构。
PyTorch允许您以类似于NumPy的方式定义和操纵张量,并且还可以将NumPy张量转换为PyTorch,反之亦然。
PyTorch驻留在割炬模块中。
按照本教程完成安装后,您应该能够运行以下代码并获取PyTorch的版本。
import torch from __future__ import print_function torch.version.__version__
输出:
'1.4.0'
让我们定义第一个张量。
使用torch.tensor()方法是执行此操作的多种方法之一。
x=torch.tensor([[2,3,4],[3,4,5]]) x
输出:
tensor([[2, 3, 4], [3, 4, 5]])
PyTorch具有is_tensor()方法,该方法检查变量是否为张量。
#Define an array of numbers. x=[10,20,30,40,50] #Check if x is a tensor torch.is_tensor(x)
输出:
False
要将数组x转换为张量,我们需要执行以下操作。
import numpy as np arr=np.array(x) # creating a numpy array from the list we defined earlier c=torch.from_numpy(arr) #create a tensor from the array torch.is_tensor(c)
输出:
True
创建张量的其他方法如下:
#Create a tensor of random normal numbers using randn() function y=torch.randn(3, 3) #Create a tensor of zeros using torch.zeros() a=torch.zeros(2,2) #Create an identity tensor using torch.eye() b=torch.eye(3,4) #torch.linspace() - returns points within a given range in a linear space. lin = torch.linspace(2,10,steps=25) #torch.logspace() - returns points in a logarithmic space log = torch.logspace(start=-10,end=10,steps=10) #torch.rand() - returns specified number of random numbers within the # interval :math:`[0, 1)` random = torch.rand(2, 3) #random permutation of values between 0 to 10 perm = torch.randperm(10) #items between 2 and 10, equally spaced by 2. If the last parameter is # ignored, step size will be 1. seq = torch.arange(2,10,2)
现在让我们检查一下上面每个张量中存储了哪些值。
print(y) print(a) print(b) print(lin) print(log) print(random) print(perm) print(seq)
输出:
tensor([[ 0.9039, 0.6291, 1.0795], [ 0.1586, 2.1939, -0.4900], [-0.1909, -0.7503, 1.9355]]) tensor([[0., 0.], [0., 0.]]) tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.]]) tensor([ 2.0000, 2.3333, 2.6667, 3.0000, 3.3333, 3.6667, 4.0000, 4.3333, 4.6667, 5.0000, 5.3333, 5.6667, 6.0000, 6.3333, 6.6667, 7.0000, 7.3333, 7.6667, 8.0000, 8.3333, 8.6667, 9.0000, 9.3333, 9.6667, 10.0000]) tensor([1.0000e-10, 1.6681e-08, 2.7826e-06, 4.6416e-04, 7.7426e-02, 1.2916e+01, 2.1544e+03, 3.5938e+05, 5.9949e+07, 1.0000e+10]) tensor([[ 0.8237, 0.5781, 0.6879], [ 0.3816, 0.7249, 0.0998]]) tensor([9, 1, 4, 5, 8, 2, 7, 6, 3, 0]) tensor([2, 4, 6, 8])
重组张量
很多时候能够修改张量的形状和结构以适合我们的算法。
PyTorch具有增加这些灵活性的几种功能。
首先,让我们定义一个张量来说明这一点。
t1=torch.rand(3,4) t1
输出:
tensor([[0.0800, 0.4987, 0.3337, 0.5070], [0.5671, 0.2567, 0.9441, 0.8524], [0.5343, 0.8898, 0.9503, 0.3900]])
以下代码转置张量:
t1.t()
tensor([[0.0800, 0.5671, 0.5343], [0.4987, 0.2567, 0.8898], [0.3337, 0.9441, 0.9503], [0.5070, 0.8524, 0.3900]])
另一种选择是使用transpose()函数。
#transpose needs dimension1 and dimension2 as attributes to transpose along the specified directions. t1.transpose(1,0)
tensor([[0.0800, 0.5671, 0.5343], [0.4987, 0.2567, 0.8898], [0.3337, 0.9441, 0.9503], [0.5070, 0.8524, 0.3900]])
重整张量可以通过多种方式完成:
t1.reshape(a,b)将返回一个新的张量,该张量具有与t1相同的数据,大小为(a,b)。
此函数将数据复制到内存的另一部分,因此可以将其视为克隆。t1.resize_(a,b)返回具有不同形状的相同张量,但是如果新形状导致元素数量少于原始张量,则某些元素将从张量中删除。
请注意,这些元素不会从内存中删除。
但是,如果新形状导致的元素数量多于张量,则这些新元素将在内存中保持未初始化状态。
下划线表明该方法是在原地执行的。t1.view(a,b)将返回一个新的张量,该张量具有与t1相同的数据,大小为(a,b)。
三种方法都以相同的方式工作。
ty=torch.randn(4,4) t2=ty.reshape(2,8) print(t2)
tensor([[-0.1995, -0.5073, 0.0820, -1.7935, -0.1631, 0.2086, 0.5033, 0.3686], [ 0.0686, 0.0247, -0.4558, -0.1373, 1.1020, 0.6841, 1.1238, -0.4326]])
Pytorch中张量的数学运算
PyTorch提供了丰富的算术运算列表,可在张量上执行这些算术运算以实现任何算法。
让我们详细了解其中一些。
张量的加法
张量加法可以使用torch.add()
函数执行。
t1 = torch.tensor([2,3,4,5]) t2 = torch.tensor([1,5,9,8]) #Adds t1 and t2 and displays the result on console torch.add(t1,t2) #Adds t1 to t2 and stores the result in t1 t1.add_(t2) #Define a new empty tensor t3=torch.tensor(4) #Add t1 and t2 and store the result in t3 torch.add(t1,t2, out= t3) print(t1) print(t3)
tensor([ 3, 8, 13, 13]) tensor([ 4, 13, 22, 21])
可以按以下方式将标量添加到张量的每个元素。
torch.add(t1,5)
tensor([8, 13, 18, 18])
张量的乘法
函数" torch.mul()"执行两个张量的元素乘法。
torch.mul(t1,t2)
tensor([ 3, 40, 117, 104])
矩阵乘法
PyTorch使用torch.mm(matrix,matrix)
和`torch.mv(matrix,vector)函数支持矩阵和向量乘法。
#Define a vector vec = torch.randn(4) #Define a matrix mat = torch.randn(3,4) print(vec) print(mat)
tensor([ 0.4888, 0.9948, -0.5621, -0.8673]) tensor([[-0.8077, 0.9913, -0.7615, -1.4975], [-0.8250, 0.9404, 0.3022, -0.1274], [-1.2982, 0.3702, 0.5074, 1.4800]])
torch.mv(mat,vec)
tensor([ 2.3182, 0.4729, -1.8350])
类似地,矩阵矩阵乘法可以使用torch.mm()函数来完成。
mat1 = torch.tensor([[2,3],[4,5]]) mat2 = torch.tensor([[4,5],[6,7]]) torch.mm(mat1,mat2)
tensor([[26, 31], [46, 55]])