PyTorch快速入门系列-01
PyTorch简介
深度学习中最常用的框架有Tensorflow、PyTorch。小编本人当初自学深度学习时,Tensorflow2.0刚出来,由于市面上并没有太多的PyTorch资料,而且Tensorflow入门简单,更快,所以选择了Tensorflow。但随着科研深入,发现大多数论文以及项目都是使用PyTorch框架,自己一脸懵逼!!!应该是自己太菜了,不能够灵活运用Tensorflow,而且身边人都开始用PyTorch,所以最终自己又转向学习PyTorch框架。(随着近年来,PyTorch在各行各业的广泛使用,而其灵活性较高,所以建议白都从PyTorch入门深度学习。)
PyTorch优点:
- 代码简洁,灵活使用:由于其基于动态图机制,使用起来相比与Tensorflow更灵活。
- DeBug方便:调试PyTorch代码,和C/C++/Python一样简单,清晰。
- 开发文档:https://pytorch.org/docs/stable/index.html
- 学术届、工业界多数算法都是PyTorch开发。
- 入门简单,快速。(方便人工智能初学者快速学习)
安装方式:后续出一个完整的安装文章,可自行先安装试试。(一般搭配环境都是安装Anaconda、PyCharm、PyTorch)。
PyTorch官方也出了一个教程,感兴趣的可以看看。
张量:Tensor
torch.tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor
官方说明:
Parameters:
data (array_like) – Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, and other types.
Keyword Arguments:
dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data.
device (torch.device, optional) – the device of the constructed tensor. If None and data is a tensor then the device of data is used. If None and data is not a tensor then the result tensor is constructed on the CPU.
requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
pin_memory (bool, optional) – If set, returned tensor would be allocated in the pinned memory. Works only for CPU tensors. Default: False.
解释:
- data:数据,可以是列表、元组、array数组或其他类型。
- dtype:数据类型,默认与data保持一致。
- device:数据所在位置:CPU/GPU。
- requires_grad:是否需要求导梯度。
- pin_memory:返回的Tensor是否被分配在固定的内存中。
看起来是不是很麻烦!接下来就不按照官方文档那样介绍了,直接简单一点,想了解更详细的话,看官网文档就行!
Tensors 张量
-
torch.is_tensor(obj)
如果obj是一个pytorch张量,则返回True
参数:obj —判断对象 -
torch.is_storage(obj)
如果obj是一个pytorch storage对象,则返回True
参数:obj —判断对象 -
torch.__set_default_tensor_type(t)
-
torch.numel(input) -> int
返回input张量中的元素个数
参数:input(Tensor)—输入张量
案例:
a = torch.randn(1,2,3,4,5)
torch.numel(a)
#a = 5
b = torch.ones((4,4))
torch.numel(b)
#b = 16
- torch.set_printoptions(precision=None,threshold=None,edgeitems=None,linewidth=None,profile=None)
设置打印选项,用的比较少。
创建操作 Creation Ops
- torch.eye(n,m=None,out=None)
返回一个2维张量,对角线位置全为1,其他位置全为0.
参数:n(int) — 行数,m(int,optional) — 列数。如果为None,则默认为n。out(Tensor.optional) — Output tensor 以上参数仅为常用参数。
返回值:对角线位置全为1,其他位置全为0的二维张量。
返回值类型:Tensor
案例:
torch.eye(3)
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
- torch.from_numpy(ndarray) -> Tensor
Numpy桥,将numpy.ndarray转换为pytorch的Tensor。返回的张量tensor和numpy的ndarray共享同一内存空间。修改一个会导致另外一个也被修改。返回的张量不能改变大小。
案例:
a = np.array([1,2,3])
torch.from_numpy(a)
tensor([1, 2, 3], dtype=torch.int32)
- torch.linspace(start,end,steps=None,out=None) -> Tensor
返回一个一维张量,包含在区间start和end上均匀间隔的steps个点。输出一维张量的长度为steps。
参数:start(float) — 序列的起始点 end(float) — 序列的最终值 steps(int) – 在start和end间生成的样本数 out(Tensor,optional) — 张量
案例:
torch.linspace(-10,10,steps=10)
tensor([-10.0000, -7.7778, -5.5556, -3.3333, -1.1111, 1.1111, 3.3333,
5.5556, 7.7778, 10.0000])
- torch.logspace(start,end,steps=None,out=None) -> Tensor
返回一个一维张量,包含在区间以10为底数的start和end之间,均匀间隔steps个点。 - torch.ones(sizes,out=None) -> Tensor
返回一个全为1的张量,形状由sizes定义。
案例:
torch.ones((2,3))
tensor([[1., 1., 1.],
[1., 1., 1.]])
- torch.rand(sizes,out=None) -> Tensor
返回一个张量,包含了从区间[0,1)的均匀分布中抽取的一组随机数,形状由sizes定义。 - torch.randn(sizes,out=None) - > Tensor
返回一个张量,包含了从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取一组随机数,形状由sizes定义。 - torch.randperm(n,out=None)
给定参数n,返回一个从0到n-1的随机数排列。
参数: n(int) — 上边界(不包含) - torch.arange(start,end,step=1,out=None) - > Tensor
返回一个一维张量,长度为floor( (end-start) / step )。包含从start到end,以step为步长的一组。序列值默认步长为1。
案例:
torch.arange(1,4)
tensor([1,2,3])
- torch.range(start,end,step=1,out=None) -> Tensor
返回一个一维张量,有floor( (end-start)/step + 1)个元素。包含在半开区间[start,end]。从start开始,以step为步长的一组值。
很少使用,建议使用torch.arange()! - torch.zeros(sizes,out=None) - > Tensor
返回一个全为标量0的张量,形状由sizes定义。
索引、切片、连接、换位(Indexing、Slicing、Joining、Mutating Ops)
- torch.cat(inputs,dimension=0) -> Tensor
在给定维度上输入的张量序列sep进行连接拼接。
torch.cat() 可以看作 torch.split() 和 torch.chunk() 的反操作。
参数:input(sequence of Tensors) — 可以是任意相同Tensor 类型的python序列 dimensions(int, optional) —沿着这个维度连接张量序列
案例:
x = torch.randn((2,3))
x
tensor([[ 0.2392, 1.6352, 0.3733],
[ 0.2606, -0.3474, -1.9230]])
torch.cat((x,x),0)
tensor([[ 0.2392, 1.6352, 0.3733],
[ 0.2606, -0.3474, -1.9230],
[ 0.2392, 1.6352, 0.3733],
[ 0.2606, -0.3474, -1.9230]])
torch.cat((x,x),1)
tensor([[ 0.2392, 1.6352, 0.3733, 0.2392, 1.6352, 0.3733],
[ 0.2606, -0.3474, -1.9230, 0.2606, -0.3474, -1.9230]])
- torch.chunk(tensor,chunks,dim=0)
在给定维度(轴)上将输入张量进行分块。
参数:tensor(Tensor) — 待分块的输入张量,chunks(int) — 分块的个数,dim(int) — 沿哪个维度进行分块 - torch.split(tensor,split_size,dim=0)
将输入张量分割成相等形状的chunks(如果可分)。如果沿指定维度的张量形状大小不能被split_size整分,则最后一个分块会小于其它分块。
参数:tensor(Tensor) — 待分割张量,split_size(int)—单个分块的形状大小,dim(int)–沿着指定维度进行分割。 - torch.squeeze(input,dim=None,out=None)
将输入张量形状中的1去除并返回。如果输入是形如(A1B1C1D),那么输出形状为:(ABCD).
当给定dim时,那么挤压操作只在给定维度上。例如,输入形状为:(A1B), squeeze(input,0)将保持张量不变,只有用squeeze(input,1),形状会变成(AB)。
注意:返回张量与输入张量共享内存,所以改变其中一个的内容会改变另一个。
参数:input(Tensor)— 输入张量,dim(int,optional)—如果给定,则input只会在给定维度挤压,out(Tensor,optional)—输出张量。
案例:
x = torch.zeros((3,1,3,1,3))
x.size()
#torch.Size([3, 1, 3, 1, 3])
torch.squeeze(x,0).size()
#torch.Size([3, 1, 3, 1, 3])
torch.squeeze(x,1).size()
#torch.Size([3, 3, 1, 3])
- torch.t(input,out=None) - > Tensor
输入一个矩阵(2维张量),并转置0,1维。可以被看作为 transpose(input,0,1)的简写。
参数:input(Tensor)—输入张量,out(Tensor,optional)—结果张量
x = torch.randn((2,3))
tensor([[ 1.7073, -0.1557, 1.4400],
[ 0.3452, 0.0751, 0.1627]])
torch.t(x)
tensor([[ 1.7073, 0.3452],
[-0.1557, 0.0751],
[ 1.4400, 0.1627]])
torch.t(x).size()
torch.Size([3, 2])
- torch.transpose(input,dim0,dim1,out=None)->Tensor
返回输入矩阵input的转置。交换维度dim0和dim1。输出张量与输入张量共享内存。所以改变其中一个,就会导致另外一个也被修改。
参数:input(Tensor)—输入张量,dim0(int)—转置的第一维度,dim1(int)—转置的第二维度
案例:
x = torch.randn(2,3)
x
tensor([[ 1.6700, 2.3639, -1.5683],
[ 0.0986, 1.5579, 0.9787]])
torch.transpose(x,0,1)
tensor([[ 1.6700, 0.0986],
[ 2.3639, 1.5579],
[-1.5683, 0.9787]])
- torch.unsqueeze(input,dim,out=None)
返回一个新的张量,对输入的制定位置插入维度1
注意:返回张量与输入张量共享内存,所以改变其中一个的内容会改变另一个。
如果dim为负,则将会被转化dim+input.dim()+1
参数:tensor(Tensor)—输入张量,dim(int)—插入维度的索引,out(Tensor,optional)—结果张量
案例:
x = torch.Tensor([1,2,3,4])
torch.unsqueeze(x,0)
#tensor([[1., 2., 3., 4.]])
x.size()
#torch.Size([4])
torch.unsqueeze(x,0).size()
#torch.Size([1, 4])