PyTorch中张量的创建方法

张量的概念

  张量,即Tensor,是PyTorch的基本数据结构。在数学概念中,张量是一个多维数组,它是标量、向量、矩阵的高维拓展。

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

GPU tensor代表数据放在GPU上。
torch.float32用得最多,卷积层的权值,以及图像预处理之后,都默认为float32。
torch.long次之,图像标签通常就是用长整型表示。

张量的创建

直接创建

torch.tensor()

torch.tensor(data, 
             dtype=None, 
             device=None, 
             requires_grad=False, 
             pin_memory=False)

功能: 从data创建tensor

  • data: 数据, 可以是list, ndarray
  • dtype: 数据类型,默认与data的一致
  • device: 所在设备, cuda/cpu
  • requires_grad:是否需要计算梯度
  • pin_memory:是否存于锁页内存,与转换效率有关,通常为False
arr = np.ones((3, 3))
print("ndarray的数据类型:", arr.dtype)
t1 = torch.tensor(arr)
t2 = torch.tensor(arr, device='cuda')
print(t1)
print(t2)
ndarray的数据类型: float64
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], device='cuda:0', dtype=torch.float64)

torch.from_numpy()

torch.from_numpy(ndarray) 

功能: 从numpy创建tensor
注意事项: 从torch.from_numpy创建的tensor与原ndarray共享内存,当修改其中一个的数据,另外一个也将会被改动

arr = np.array([[1, 2, 3], [4, 5, 6]])
t = torch.from_numpy(arr)
print(arr)
print(t)

print("\n修改arr")
arr[0, 0] = 0
print(arr)
print(t)

print("\n修改tensor")
t[0, 0] = -1
print(arr)
print(t)
[[1 2 3]
 [4 5 6]]
tensor([[1, 2, 3],
        [4, 5, 6]], dtype=torch.int32)

修改arr
[[0 2 3]
 [4 5 6]]
tensor([[0, 2, 3],
        [4, 5, 6]], dtype=torch.int32)

修改tensor
[[-1  2  3]
 [ 4  5  6]]
tensor([[-1,  2,  3],
        [ 4,  5,  6]], dtype=torch.int32)

依据数值创建

torch.zeros()

torch.zeros(size, 
            out=None, 
            dtype=None, 
            layout=torch.strided, 
            device=None, 
            requires_grad=False)

功能: 依size创建全0张量

  • size: 张量的形状,如(3, 3)、(3, 224,224)
  • out : 输出的张量,将创建的tensor赋值给out,共享内存
  • dtype : 数据类型
  • layout : 内存中布局形式,有 strided,sparse_coo(稀疏张量使用)等
  • device : 所在设备,cuda/cpu
  • requires_grad:是否需要计算梯度
out_t = torch.tensor([1])
print(out_t)
t = torch.zeros((3, 3), out=out_t)
print(t)
print(out_t)
print(id(t), id(out_t), id(t) == id(out_t))
tensor([1])
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
1752193781416 1752193781416 True

torch.zeros_like()

torch.zeros_like(input, 
                 dtype=None, 
                 layout=None, 
                 device=None, 
                 requires_grad=False)

功能: 依input形状创建全0张量

  • intput: 创建与input同形状的全0张量
  • dtype : 数据类型
  • layout : 内存中布局形式,有 strided,sparse_coo(稀疏张量使用)等
  • device : 所在设备,cuda/cpu
  • requires_grad:是否需要计算梯度
t1 = torch.tensor([1, 1, 1])
t2 = torch.zeros_like(t1)
print(t1)
print(t2)
tensor([1, 1, 1])
tensor([0, 0, 0])

torch.ones() 和 torch.ones_like()

torch.ones(size, 
           out=None, 
           dtype=None, 
           layout=torch.strided, 
           device=None, 
           requires_grad=False
           
torch.ones_like(input, 
                dtype=None, 
                layout=None, 
                device=None, 
                requires_grad=False)

功能: 创建全1张量,用法与zero相同

torch.full() 和 torch.full_like()

torch.full(size, 
           fill_value, 
           out=None, 
           dtype=None, 
           layout=torch.strided, 
           device=None, 
           requires_grad=False)
           
torch.full_like(input, 
                fill_value, 
                dtype=None, 
                layout=None, 
                device=None, 
                requires_grad=False)

功能: 创建自定义数值的张量,用法与zero相同

  • fill_value:填充张量的值
t1 = torch.full((3, 3), 9)
print(t1)
t2 = torch.full_like(t1, 8)
print(t2)
tensor([[9., 9., 9.],
        [9., 9., 9.],
        [9., 9., 9.]])
tensor([[8., 8., 8.],
        [8., 8., 8.],
        [8., 8., 8.]])

torch.arange()

torch.arange(start=0, 
             end, 
             step=1, 
             out=None, 
             dtype=None, 
             layout=torch.strided, 
             device=None, 
             requires_grad=False)

功能: 创建等差的1维张量
注意事项: 数值区间为[start, end) ,end取不到

  • start: 数列起始值
  • end : 数列结束值
  • step: 数列公差,默认为1
t = torch.arange(2, 10, 2)
print(t)
tensor([2, 4, 6, 8])

torch.linspace()

torch.linspace(start, 
               end, 
               steps=100, 
               out=None, 
               dtype=None, 
               layout=torch.strided, 
               device=None, 
               requires_grad=False) 

功能: 创建均分的1维张量
注意事项: 数值区间为[start, end],包含end

  • start: 数列起始值
  • end : 数列结束值
  • steps: 数列长度
t1 = torch.linspace(2, 10, 5)
t2 = torch.linspace(2, 10, 6)
print(t1)
print(t2)
tensor([ 2.,  4.,  6.,  8., 10.])
tensor([ 2.0000,  3.6000,  5.2000,  6.8000,  8.4000, 10.0000])

torch.logspace()

torch.logspace(start, 
               end, 
               steps=100, 
               base=10.0, 
               out=None, 
               dtype=None, 
               layout=torch.strided, 
               device=None, 
               requires_grad=False)

功能: 创建从 base的start次幂 到 base的end次幂 的等比1维张量
注意事项: 数值区间为[start, end],包含end

  • start:数列起始幂次
  • end:数列结束幂次
  • steps:数列长度
  • base:数列公比,默认为10
t = torch.logspace(0, 4, 5, 3)
print(t)
tensor([ 1.,  3.,  9., 27., 81.])

torch.eye()

torch.eye(n, 
          m=None, 
          out=None, 
          dtype=None, 
          layout=torch.strided, 
          device=None, 
          requires_grad=False) 

功能: 创建单位对角矩阵( 2维张量)
注意事项: 默认为方阵

  • n: 矩阵行数
  • m : 矩阵列数
t1 = torch.eye(3)
t2 = torch.eye(3, 5)
print(t1)
print(t2)
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
tensor([[1., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 0., 1., 0., 0.]])

依概率分布创建张量

torch.normal()

torch.normal(mean, 
             std, 
             size, 
             out=None)

功能: 从给定参数的离散正态分布(高斯分布)中抽取随机数创建张量

注意事项: 共有四种模式

  1. mean为标量,std为标量
  2. mean为标量,std为张量
  3. mean为张量,std为标量
  4. mean为张量,std为张量
  • mean : 均值
  • std : 标准差
  • size:仅在mean和std均为标量时使用,表示创建张量的形状
# mean为标量,std为标量
t1 = torch.normal(0, 1, (4,))
print(t1, "\n")

# mean为张量,std为张量,依次取mean和std中的值作为均值和标准差构成正态分布,从每个正太分布中随机抽取一个数字
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t = torch.normal(mean, std)
print("mean:{}\nstd:{}\n{}".format(mean, std, t))
tensor([-0.0209,  1.2597, -0.7261,  0.8786]) 

mean:tensor([1., 2., 3., 4.])
std:tensor([1., 2., 3., 4.])
tensor([ 0.0653,  3.8435, -2.2774,  8.5908])

torch.randn() 和 torch.randn_like()

torch.randn(size, 
            out=None, 
            dtype=None, 
            layout=torch.strided, 
            device=None, 
            requires_grad=False)

torch.randn_like(input, 
                 dtype=None, 
                 layout=None, 
                 device=None, 
                 requires_grad=False)

功能: 从标准正态分布(均值为0,标准差为1)中抽取随机数创建张量

torch.rand() 和 torch.rand_like()

 torch.rand(size, 
            out=None, 
            dtype=None, 
            layout=torch.strided, 
            device=None, 
            requires_grad=False) 

torch.rand_like(input,
			    dtype=None, 
                layout=torch.strided, 
            	device=None, 
            	requires_grad=False) 

功能: 从[0, 1)上的均匀分布中抽取随机数创建张量

torch.randint() 和 torch.randint_like()

torch.randint(low=0, 
              high, 
              size, 
              out=None, 
              dtype=None, 
              layout=torch.strided, 
              device=None, 
              requires_grad=False)

torch.randint_like(input,
				   dtype=None, 
              	   layout=torch.strided, 
                   device=None, 
                   requires_grad=False)

功能: 从[low, high)上的整数中抽取随机数创建张量

torch.randperm()

 torch.randperm(n, 
                out=None, 
                dtype=torch.int64, 
                layout=torch.strided, 
                device=None, 
                requires_grad=False)

功能: 生成从0到n-1的随机排列,可以用来生成乱序的索引

  • n : 张量的长度

torch.bernoulli()

torch.bernoulli(input, 
                generator=None, 
                out=None)

功能: 从伯努利分布中抽取二元随机数(0或者1),输入中所有值必须在[0, 1]区间,输出张量的第i个元素值,将依输入张量的第i个概率值等于1。

  • input : 概率值
t1 = torch.rand((4,))
t = torch.bernoulli(t1)
print(t1)
print(t)
tensor([0.5793, 0.7866, 0.6888, 0.2221])
tensor([0., 1., 0., 0.])

创建未初始化的张量

torch.empty()

torch.empty(size, 
            out=None, 
            dtype=None, 
            layout=torch.strided, 
            device=None, 
            requires_grad=False)

功能: 创建一个未被初始化数值的tensor,tensor的大小由size确定

t1 = torch.tensor([1, 2, 3])
print(t1)
t2 = torch.empty(size=[2, 3], out=t1)
print(t2)
tensor([1, 2, 3])
tensor([[                1,                 2,                 3],
        [30962681235898419, 31525592536121462, 32088624093986937]])

说明: t2与t1共享内存地址,由于t2未初始化,所以显示的前3个元素是t1的值,后面的元素是乱码;如果t2初始化了,那么打印t1和t2将显示t2的值。

发布了9 篇原创文章 · 获赞 0 · 访问量 299

猜你喜欢

转载自blog.csdn.net/SakuraHimi/article/details/104466849