1. Tensor概念
  2. Tensor创建
    1. 直接创建
    2. 依据数值创建
    3. 依据概率创建

01. 张量的概念

image.png

1.1 Tensor 与 Variable

张量表示一个多维数组,但是在PyTorch中不仅仅表示多维数组,其还是自动求导的关键。

  • Variabletorch.autograd 中的数据类型
    • Variable0.4.0版本 之前的重要数据类型。在该版本之后, Variable 并入了 Tensor ,不再需要 variable 数据类型。
  • 主要用于封装 Tensor ,进行自动求导

image.png

  • data : 被包装的 Tensor
  • grad : data 的梯度
  • grad_fn : 创建 TensorFunction ,是自动求导的关键
  • requires_grad : 指示是否需要梯度
  • is_leaf : 指示是否是叶子结点(张量)
    • PyTorch0.4.0 版本开始, Variable 并入 Tensor

image.png

  • dtype : 张量的数据类型, PyTorch 提供了9钟数据类型。如 torch.FloatTensortorch.cuda.FloatTensor

image.png

  • shape : 张量的形状,如 (64, 3, 224, 224)
  • device : 张量所在设备,GPU/CPU,是加速的关键

    02. 张量的创建

    2.1 直接创建

  • torch.tensor()
  • image.png
  • 功能:从 data 创建 Tensor

    • data : 数据,可以使 listnumpy数组
    • dtype : 数据类型,默认和 data 一致
    • device : 所在设备,gpu or cpu
    • requires_grad : 是否需要梯度
    • pin_memory : 是否存于锁页内存,通常设置为 False
      1. arr = np.ones((3, 3))
      2. print("ndarray的数据类型:{}".format(arr.dtype))
      3. t = torch.tensor(arr, device='cpu')
      4. # t = torch.tensor(arr, device='cuda') # cuda not gpu
      5. print(t)
  • torch.from_numpy(ndarray)

  • 功能:从 numpy 创建 tensor

image.png

NOTE : torch.from_numpy 创建的 tensor 于原 ndarray 共享内存,当修改其中一个的数据,另外一个也将会被改动

  1. arr = np.array([[1, 2, 3], [4, 5, 6]])
  2. t = torch.from_numpy(arr)
  3. print("numpy arr is {}".format(arr))
  4. print("tensor from numpy t is {}".format(t))
  5. print("\n修改arr")
  6. arr[0, 0] = 0
  7. print("modified numpy arr is {}".format(arr))
  8. print("modified tensor from numpy t is {}".format(t))
  9. print("\n修改tensor")
  10. t[0, 0] = -1
  11. print("numpy arr is {}".format(arr))
  12. print("modified tensor from numpy t is {}".format(t))

2.2 依据数值创建

2.2.1 torch.zeros()torch.ones()

image.pngimage.png

  • 功能:依size创建 全0 或 全1 的张量

    • size : 张量的形状,如(3, 3)、(3, 224, 224)
    • out : 输出的张量
    • layout : 内存中布局形式,有 stridedsparse_coo
    • device : 所在设备,gpu/cpu
    • requires_grad : 是否需要梯度
      1. out_t = torch.tensor([1])
      2. print(out_t)
      3. t = torch.zeros((3, 3), out=out_t) # t和out_t是同一个数据
      4. print(t, '\n', out_t)
      5. print(id(t), id(out_t), id(t) == id(out_t)) # print memory address

      2.2.2 torch.zeros_like()torch.ones_like()

      image.pngimage.png
  • 功能:依 input 形状创建全0张量

  • intput : 创建与 input 同形状的全0张量
  • dtype : 数据类型
  • layout : 内存中布局形式

    1. t = torch.tensor([[1, 2, 3], [4, 5, 6]])
    2. out_t = torch.zeros_like(t)
    3. print("t is {}".format(t))
    4. print("out t is {}".format(out_t))

    2.2.3 torch.full()torch.full_like()

    image.png

  • 功能:依 input 形状创建指定数据的张量

  • size : 张量的形状,如(3, 3)
  • fill_value : 张量的值 ```python t = torch.full((3, 3), 1) print(t)

t = torch.tensor([[1, 2, 3], [4, 5, 6]]) out_t = torch.full_like(t, 1)

  1. <a name="hkkGe"></a>
  2. ### 2.2.4 `torch.arange()`
  3. - 功能:创建等差的1维张量
  4. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/353587/1588236871064-22ff1f9a-b285-4164-9ee0-c8a372a4de4b.png#align=left&display=inline&height=172&margin=%5Bobject%20Object%5D&name=image.png&originHeight=172&originWidth=401&size=29945&status=done&style=none&width=401)
  5. - `start` : 数列起始值
  6. - `end` : 数列“结束值”
  7. - `step` : 数列公差,默认为1
  8. > 注意事项:数值区间为[start, end)
  9. ```python
  10. t = torch.arange(2, 10, 2)

2.2.5 torch.linspace()

  • 功能:创建均分的1维张量

image.png

  • start : 数列起始值

  • end : 数列结束值

  • steps : 数列长度

    注意事项:数值区间为[start, end]

t = torch.linspace(2, 10, 6)

2.2.6 torch.logspace()

image.png

  • 功能:创建对数均分的1维张量
    • start : 数列起始值
    • end : 数列结束值
    • steps: 数列长度
    • base : 对数函数的底,默认为10

      注意事项:长度为steps,底为base

2.2.7 torch.eye()

image.png

  • 功能:创建单位对角矩阵(2维张量)
    • n : 矩阵行数
    • m : 矩阵列数

      注意事项:默认为方阵

2.3 依概率分布创建张量

2.3.1 torch.normal()

image.png

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

    • mean : 均值
    • std : 标准差

      2.3.2 torch.normal()

      image.png
      四种模式,生成的结果不同:
  • mean为标量,std为标量

  • mean为标量,std为张量
  • mean为张量,std为标量
  • mean为张量,std为张量 ```python

    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:{} \n std:{}”.format(mean, std)) print(t_normal)

mean:标量 std: 标量

t_normal = torch.normal(0., 1., size=(4,)) print(t_normal)

mean:张量 std: 标量

mean = torch.arange(1, 5, dtype=torch.float) std = 1 t_normal = torch.normal(mean, std) print(“mean:{}\nstd:{}”.format(mean, std)) print(t_normal)

mean:标量 std: 张量

std = torch.arange(1, 5, dtype=torch.float) mean = 1 t_normal = torch.normal(mean, std) print(“mean:{}\nstd:{}”.format(mean, std)) print(t_normal)

<a name="z4K99"></a>
### 2.3.3 `torch.randn()` 、 `torch.randn_like()` 
![image.png](https://cdn.nlark.com/yuque/0/2020/png/353587/1588238043754-25a4ad46-b7f3-4a2c-bfb9-03c434f67963.png#align=left&display=inline&height=133&margin=%5Bobject%20Object%5D&name=image.png&originHeight=133&originWidth=382&size=25278&status=done&style=none&width=382)

- 功能:生成**标准正态分布**
   - size : 张量的形状
```python
# t = torch.randn(3)
t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float32)
out_t = torch.randn_like(t)
print(out_t)

image.png 该API可能会生成浮点数,但是tensor的数据类型是整形,所以需要转换一下数据类型。 解决方案:tensor的数据类型换一下。 dtype=torch.float32

2.3.4 torch.rand()torch.rand_like()

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

image.png

2.3.5 torch.randint()torch.randint_like()

image.png

  • 功能:区间[low, high)生成整数均匀分布

    • size : 张量的形状
      # t = torch.randint(3, 10, (5,5))
      t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
      out_t = torch.randint_like(input=t, low=3, high=10)
      print(out_t)
      

      2.3.6 torch.randperm()

      image.png
  • 功能:生成生成从 [0, n) 的随机排列,经常用来生成随机索引。

    • n : 张量的长度
      t = torch.randperm(10)
      

      2.3.7 torch.bernoulli()

      image.png
  • 功能:以 input 为概率,生成伯努力分布(0-1分布,两点分布)

    • input : 概率值
      a = torch.empty(3, 3).uniform_(0, 1)  # generate a uniform random matrix with range [0, 1]
      t = torch.bernoulli(a)
      print(t)