thumbnail: https://image.zhangxiann.com/...
toc: true
date: 2020/2/5 20:39:20
disqusId: zhangxian
categories:

  • PyTorch

tags:

  • AI
  • Deep Learning

本章代码:

  • https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/tensor_introduce1.py
  • https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/tensor_introduce1.py

Tensor 的概念

Tensor 中文为张量。张量的意思是一个多维数组,它是标量、向量、矩阵的高维扩大。

标量能够称为 0 维张量,向量能够称为 1 维张量,矩阵能够称为 2 维张量,RGB 图像能够示意 3 维张量。你能够把张量看作多维数组。

<!--more-->

<div align="center"></div>

Tensor 与 Variable

在 PyTorch 0.4.0 之前,torch.autograd 包中存在 Variable 这种数据类型,次要是用于封装 Tensor,进行主动求导。Variable 次要蕴含上面几种属性。

  • data: 被包装的 Tensor。
  • grad: data 的梯度。
  • grad_fn: 创立 Tensor 所应用的 Function,是主动求导的要害,因为依据所记录的函数能力计算出导数。
  • requires_grad: 批示是否须要梯度,并不是所有的张量都须要计算梯度。
  • is_leaf: 批示是否叶子节点(张量),叶子节点的概念在计算图中会用到,前面具体介绍。

<div align="center"></div>

在 PyTorch 0.4.0 之后,Variable 并入了 Tensor。在之后版本的 Tensor 中,除了具备下面 Variable 的 5 个属性,还有另外 3 个属性。

  • dtype: 张量的数据类型,如 torch.FloatTensor,torch.cuda.FloatTensor。
  • shape: 张量的形态。如 (64, 3, 224, 224)
  • device: 张量所在设施 (CPU/GPU),GPU 是减速计算的要害

<div align="center"></div>

对于 dtype,PyTorch 提供了 9 种数据类型,共分为 3 大类:float (16-bit, 32-bit, 64-bit)、integer (unsigned-8-bit ,8-bit, 16-bit, 32-bit, 64-bit)、Boolean。模型参数和数据用的最多的类型是 float-32-bit。label 罕用的类型是 integer-64-bit。

<div align="center"></div>

Tensor 创立的办法

间接创立 Tensor

torch.tensor()

torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False)
  • data: 数据,能够是 list,numpy
  • dtype: 数据类型,默认与 data 的统一
  • device: 所在设施,cuda/cpu
  • requires_grad: 是否须要梯度
  • pin_memory: 是否存于锁页内存

代码示例:

arr = np.ones((3, 3))print("ndarray的数据类型:", arr.dtype)# 创立寄存在 GPU 的数据# t = torch.tensor(arr, device='cuda')t= torch.tensor(arr)print(t)

输入为:

ndarray的数据类型: float64tensor([[1., 1., 1.],        [1., 1., 1.],        [1., 1., 1.]], dtype=torch.float64)

torch.from_numpy(ndarray)

从 numpy 创立 tensor。利用这个办法创立的 tensor 和原来的 ndarray 共享内存,当批改其中一个数据,另外一个也会被改变。

<div align="center"></div>

代码示例:

arr = np.array([[1, 2, 3], [4, 5, 6]])t = torch.from_numpy(arr)# 批改 array,tensor 也会被批改# print("\n批改arr")# arr[0, 0] = 0# print("numpy array: ", arr)# print("tensor : ", t)# 批改 tensor,array 也会被批改print("\n批改tensor")t[0, 0] = -1print("numpy array: ", arr)print("tensor : ", t)

输入为:

批改tensornumpy array:  [[-1  2  3] [ 4  5  6]]tensor :  tensor([[-1,  2,  3],        [ 4,  5,  6]], dtype=torch.int32)

依据数值创立 Tensor

torch.zeros()

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

性能:依据 size 创立全 0 张量

  • size: 张量的形态
  • out: 输入的张量,如果指定了 out,那么torch.zeros()返回的张量和 out 指向的是同一个地址
  • layout: 内存中布局模式,有 strided,sparse_coo 等。当是稠密矩阵时,设置为 sparse_coo 能够缩小内存占用。
  • device: 所在设施,cuda/cpu
  • requires_grad: 是否须要梯度

代码示例:

out_t = torch.tensor([1])# 这里制订了 outt = torch.zeros((3, 3), out=out_t)print(t, '\n', out_t)# id 是取内存地址。最终 t 和 out_t 是同一个内存地址print(id(t), id(out_t), id(t) == id(out_t))

输入是:

tensor([[0, 0, 0],        [0, 0, 0],        [0, 0, 0]])  tensor([[0, 0, 0],        [0, 0, 0],        [0, 0, 0]])2984903203072 2984903203072 True

torch.zeros_like

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

性能:依据 input 形态创立全 0 张量

  • input: 创立与 input 同形态的全 0 张量
  • dtype: 数据类型
  • layout: 内存中布局模式,有 strided,sparse_coo 等。当是稠密矩阵时,设置为 sparse_coo 能够缩小内存占用。

同理还有全 1 张量的创立办法:torch.ones()torch.ones_like()

torch.full(),torch.full_like()

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

性能:创立自定义数值的张量

  • size: 张量的形态,如 (3,3)
  • fill_value: 张量中每一个元素的值

代码示例:

t = torch.full((3, 3), 1)print(t)

输入为:

tensor([[1., 1., 1.],        [1., 1., 1.],        [1., 1., 1.]])

torch.arange()

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

性能:创立等差的 1 维张量。留神区间为[start, 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]

  • start: 数列起始值
  • end: 数列完结值
  • steps: 数列长度 (元素个数)

代码示例:

# t = torch.linspace(2, 10, 5)t = torch.linspace(2, 10, 6)print(t)

输入为:

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)

性能:创立对数均分的 1 维张量。数值区间为 [start, end],底为 base。

  • start: 数列起始值
  • end: 数列完结值
  • steps: 数列长度 (元素个数)
  • base: 对数函数的底,默认为 10

代码示例:

# t = torch.linspace(2, 10, 5)t = torch.linspace(2, 10, 6)print(t)

输入为:

tensor([ 2.0000,  3.6000,  5.2000,  6.8000,  8.4000, 10.0000])

torch.eye()

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

性能:创立单位对角矩阵( 2 维张量),默认为方阵

  • n: 矩阵行数。通常只设置 n,为方阵。
  • m: 矩阵列数

依据概率创立 Tensor

torch.normal()

torch.normal(mean, std, *, generator=None, out=None)

性能:生成正态分布 (高斯分布)

  • mean: 均值
  • std: 标准差

有 4 种模式:

  1. mean 为标量,std 为标量。这时须要设置 size。

    代码示例:

    # mean:标量 std: 标量# 这里须要设置 sizet_normal = torch.normal(0., 1., size=(4,))print(t_normal)

    输入为:

    tensor([0.6614, 0.2669, 0.0617, 0.6213])
  2. mean 为标量,std 为张量
  3. mean 为张量,std 为标量

    代码示例:

    # mean:张量 std: 标量mean = torch.arange(1, 5, dtype=torch.float)std = 1t_normal = torch.normal(mean, std)print("mean:{}\nstd:{}".format(mean, std))print(t_normal)

    输入为:

    mean:tensor([1., 2., 3., 4.])std:1tensor([1.6614, 2.2669, 3.0617, 4.6213])

    这 4 个数采样散布的均值不同,然而方差都是 1。

  4. mean 为张量,std 为张量

    代码示例:

    # mean:张量 std: 张量mean = torch.arange(1, 5, dtype=torch.float)std = torch.arange(1, 5, dtype=torch.float)t_normal = torch.normal(mean, std)print("mean:{}\nstd:{}".format(mean, std))print(t_normal)

    输入为:

    mean:tensor([1., 2., 3., 4.])std:tensor([1., 2., 3., 4.])tensor([1.6614, 2.5338, 3.1850, 6.4853])

    其中 1.6614 是从正态分布 $N(1,1)$ 中采样失去的,其余数字以此类推。

torch.randn() 和 torch.randn_like()

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

性能:生成规范正态分布。

  • size: 张量的形态

torch.rand() 和 torch.rand_like()

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

性能:在区间 [0, 1) 上生成均匀分布。

torch.randint() 和 torch.randint_like()

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

性能:在区间 [low, high) 上生成整数均匀分布。

  • size: 张量的形态

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)

性能:以 input 为概率,生成伯努利散布 (0-1 散布,两点散布)

  • input: 概率值

参考资料

  • 深度之眼 PyTorch 框架班


如果你感觉这篇文章对你有帮忙,无妨点个赞,让我有更多能源写出好文章。

我的文章会首发在公众号上,欢送扫码关注我的公众号张贤同学

<div align="center"></div>