在Pytorch中,torch.Tensor是存储和变换数据的主要工具,其形式类似于Numpy中的多为数组,这里被称为张量。于Numpy中的数组相比,torch.Tensor中提供了GPU计算和自动求梯度等更多的功能,从而使Tensor更适合深度学习。
“张量”是带有维度的:
0维张量:标量
1维张量:1维数组
2维张量:2维数组(矩阵)
2.1 torch.Tensor中的属性
-
data: 被包装的Tensor
-
grad: data的梯度
-
grad_fn: 创建Tensor的Function,如加法,乘法,这个操作在求导过程中需要用到,所以需要将其记录下来。
-
requires_grad: 指示是否需要计算梯度
-
is_leaf: 指示是否是叶子结点
-
dtype: 张量的数据类型,如 torch.FloatTensor, torch.cuda.FloatTensor
-
shape: 张量的形状,如(64, 3, 224, 224)
-
device: 张量所在设备,GPU/CPU,只有在GUP上才可以使用GUP进行加速运算
Data Type | dtype | CPU tensor | GPU tensor |
---|---|---|---|
32-bit floating point | torch.float32 or torch.float | torch.FloatTensor | torch.cuda.FloatTensor |
64-bit floating point | torch.float64 or torch.double | torch.DoubleTensor | torch.cuda.DoubleTensor |
16-bit floating point | torch.float16 or torch.half | torch.HalfTensor | torch.cuda.HalfTensor |
8-bit integer(unsigned) | torch.uint8 | torch.ByteTensor | torch.cuda.ByteTensor |
8-bit integer(signed) | torch.int8 | torch.CharTensor | torch.cuda.CharTensor |
16-bit integer(signed) | torch.int16 or torch.short | torch.ShortTensor | torch.cuda.ShortTensor |
32-bit integer(signed) | torch.int32 or torch.int | torch.IntTensor | torch.cuda.IntTensor |
64-bit integer(signed) | torch.int64 or torch.long | torch.LongTensor | torch.cuda.LongTensor |
Boolean | torch.bool | torch.BoolTensor | torch.cuda.BoolTensor |
2.2 创建张量
2.2.1 torch.tensor
- 函数功能:指定元素值创建张量
torch.tensor(data,
dtype=None,
device=None,
requires_grad=False,
pin_memory=False)
-
data: 数据, 可以是list, ndarray
-
dtype: 数据类型,默认与data的一致
-
device: 所在设备, cuda/cpu
-
requires_grad:是否需要计算梯度
-
pin_memory:是否存于锁页内存,与转换效率有关,通常为False
-
举例
import torch #创建3×3的张量 x = torch.tensor([[1,2,3], [4,5,6], [7,8,9]]) print(x)
输出:
tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
2.2.2 torch.empty
-
功能:创建一个未初始化张量
torch.empty(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False)
- size: 张量大小
- out:使用一个已有张量作为输出,并拓展该输出为size的大小,新建张量与已有张量共享内存
-
举例
import torch y=torch.tensor([[1,2,3]]) print(y) z=torch.empty(size=[3,3],out=y) print(z) y[1]=1100 print(y)
输出:
tensor([[1, 2, 3]]) tensor([[ 1, 2, 3], [31244147623002222, 14355640430624878, 33214519704879196], [28710945846722675, 29555336417116210, 29555366481887330]]) tensor([[ 1, 2, 3], [ 1100, 1100, 1100], [28710945846722675, 29555336417116210, 29555366481887330]])
【说明】:由于输出out是y,所以y与z共享内存,原有的y的前三个内存单元值不变,另外创建6个值任意的内存单元,此时y也变成了3×3的张量。当y修改第2维元素为1100后,张量第二维全部变为1100
2.2.3 torch.zeros
-
函数功能:创建一个全0的张量
torch.zeros(size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
-
size: 张量的形状,如(3, 3)、(3, 224,224)
-
out : 输出的张量,将创建的tensor赋值给out,共享内存
-
dtype : 数据类型
-
layout : 内存中布局形式,有 strided,sparse_coo(稀疏张量使用)等
-
device : 所在设备,cuda/cpu
-
requires_grad:是否需要计算梯度
-
-
举例
import torch #创建5×3的全0张量 x = torch.zeros(5,3) print(x)
输出:
tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
2.2.4 torch.zeros_like
-
函数功能:生成和括号内变量维度维度一致的全是零的张量
torch.zeros_like(input, dtype=None, layout=None, device=None, requires_grad=False)
- intput: 输入张量
- dtype : 数据类型
- layout : 内存中布局形式,有 strided,sparse_coo(稀疏张量使用)等
- device : 所在设备,cuda/cpu
- requires_grad:是否需要计算梯度
-
举例:
import torch a = torch.ones(3,3) b = torch.zeros_like(a) print(a) print(b)
输出:
tensor([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]) tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
2.2.5 tensor.new_ones
-
函数功能:返回一个指定大小的用1填充的张量。 默认返回的Tensor具有与此张量相同的torch.dtype和torch.device
new_ones(size, dtype=None, device=None, requires_grad=False)
-
举例:
import torch x = torch.tensor([[1,2,3], [4,5,6], [7,8,9]]) a = x.new_ones(5,3,dtype = torch.float64) b = x.new_ones(5,3) print(a.dtype) print(b.dtype)
输出:
torch.float64 torch.int64
2.2.6 torch.from_numpy
-
从numpy创建tensor
-
【注意】:从torch.from_numpy创建的tensor与原ndarray共享内存,当修改其中一个的数据,另外一个也将会被改动
import torch import numpy as np arr = np.array([1,2,3]) arr_t = torch.from_numpy(arr) print(arr) print(arr_t) arr[1]=10 print(arr) print(arr_t)
输出:
[1 2 3] tensor([1, 2, 3], dtype=torch.int32) [ 1 10 3] tensor([ 1, 10, 3], dtype=torch.int32)
2.2.7 torch.eye
-
函数功能:返回一个2维张量,对角线位置全1,其它位置全0
torch.eye(n, m=None, out=None)
- n:行数
- m:列数。如果为None,则默认为n
- out:输出张量
-
举例
import torch a = torch.eye(5,2) b = torch.eye(3) print(a) print(b)
输出:
tensor([[1., 0.], [0., 1.], [0., 0.], [0., 0.], [0., 0.]]) tensor([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
2.2.8 torch.rand
-
函数功能:返回一个张量,包含了从区间[0,1)的均匀分布中抽取的一组随机数,形状由可size定义。
torch.rand(*sizes, out=None)
-
举例
import torch #创建5×3的随机初始化张量 x = torch.rand(5,3) print(x)
输出:
tensor([[0.4909, 0.1955, 0.5341], [0.5199, 0.7508, 0.1953], [0.8536, 0.0351, 0.9054], [0.6870, 0.2469, 0.8732], [0.0733, 0.9238, 0.6424]])
2.2.9 torch.randn
-
函数功能:返回一个张量,包含了从标准正态分布(均值为0,方差为 1)中抽取一组随机数。
torch.randn(*sizes, out=None)
2.2.10 torch.normal
-
函数功能:返回一个张量,包含从给定参数
means
,std
的离散正态分布中抽取随机数。 均值means
是一个张量,包含每个输出元素相关的正态分布的均值。std
是一个张量,包含每个输出元素相关的正态分布的标准差。 均值和标准差的形状不须匹配,但每个张量的元素个数须相同。torch.normal(means, std, out=None)
-
举例:
import torch print(torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)))
输出:
tensor([ 2.1880, 1.3159, 4.0056, 3.5005, 5.4269, 5.5967, 6.8929, 8.0069,8.9428, 10.1045])
2.2.11 torch.randperm
-
函数功能:给定参数
n
,返回一个从0
到n -1
的随机整数排列。torch.randperm(n, out=None)
-
举例
import torch print(torch.randperm(10))
输出:
tensor([2, 0, 3, 8, 9, 6, 1, 5, 4, 7])
2.2.12 torch.arange
-
函数功能:返回一个1维张量,长度为
floor((end−start)/step)
。包含从start
到end
(不包含end),以step
为步长的一组序列值(默认步长为1)。torch.arange(start, end, step=1, out=None)
-
举例
import torch a = torch.arange(1,9,2) b = torch.arange(1,10,2) print(a) print(b)
输出:
tensor([1, 3, 5, 7]) tensor([1, 3, 5, 7, 9])
2.2.13 torch.linspace
-
函数功能:返回一个1维张量,包含在区间
start
和end
上均匀间隔的steps
个点。torch.linspace(start, end, steps=100, out=None)
-
举例
import torch print(torch.linspace(3,10,steps=2)) print(torch.linspace(3,10,steps=3)) print(torch.linspace(3,10,steps=4)) print(torch.linspace(3,10,steps=5))
输出:
tensor([ 3., 10.]) tensor([ 3.0000, 6.5000, 10.0000]) tensor([ 3.0000, 5.3333, 7.6667, 10.0000]) tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000])