1. 张量的操作:拼接、切分、索引和变换
  2. 张量的数学运算
  3. 线性回归

一、张量的操作

01. 张量拼接

1.1 torch.cat()

image.png

  • 功能:将张量按维度dim进行拼接

    • tensors : 张量序列
    • dim : 要拼接的维度
      1. t = torch.ones((2, 3))
      2. t_0 = torch.cat([t, t], dim=0)
      3. t_1 = torch.cat([t, t, t], dim=1)
      4. print("t_0:{} \n shape:{} \n t_1:{} \n shape:{}".format(t_0, t_0.shape, t_1, t_1.shape))

      1.2 torch.stack()

      image.png
  • 功能:会创建一个新的维度,在新创建的维度dim上进行拼接

    • tensors : 张量序列
    • dim : 要拼接的维度 ```python t = torch.ones((2, 3)) t_stack = torch.stack([t, t, t], dim=0)

      if dim=0, 会将原有维度往后移动一个维度,在维度0新建一个维度进行拼接

print(“\nt_stack:{} shape:{}”.format(t_stack, t_stack.shape))

  1. > NOTE
  2. > - `cat()` 方法不会扩张张量的维度
  3. > - `stack()` 方法会扩展张量的维度
  4. <a name="0CkdJ"></a>
  5. ## 02. 张量切分
  6. <a name="GTk4a"></a>
  7. ### 2.1 `torch.chunk()`
  8. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/353587/1588302749513-a17972b7-e618-4e6d-aec6-0ef73daf4ad8.png#align=left&display=inline&height=68&margin=%5Bobject%20Object%5D&name=image.png&originHeight=68&originWidth=297&size=8464&status=done&style=none&width=297)
  9. - 功能:将张量按维度 `dim` 进行平均切分
  10. - 返回值:张量列表
  11. - `input` : 要切分的张量
  12. - `chunks` : 要切分的份数
  13. - `dim` : 要切分的维度
  14. > 注意事项:若不能整除,最后一份张量小于其他张量
  15. ```python
  16. a = torch.ones((2, 7)) # 7
  17. list_of_tensors = torch.chunk(a, dim=1, chunks=3) # 3
  18. for idx, t in enumerate(list_of_tensors):
  19. print("第{}个张量:{}, shape is {}".format(idx+1, t, t.shape))
  • 结果:

image.png

2.2 torch.spilt()

image.png

  • 功能:将张量按维度 dim 进行切分
  • 返回值:张量列表
    • tensor : 要切分的张量
    • split_size_or_sections : 为int时,表示每一份的长度;为list时,按list元素切分
    • dim : 要切分的维度
      t = torch.ones((2, 5))
      list_of_tensors_01 = torch.split(t, 2, dim=1)  # [2 , 1, 2]
      for idx, t in enumerate(list_of_tensors_01):
      print("第{}个张量:{}, shape is {}".format(idx + 1, t, t.shape))
      
      image.png
      t = torch.ones((2, 5))
      list_of_tensors_02 = torch.split(t, [2, 1, 2], dim=1)  # [2 , 1, 2]
      for idx, t in enumerate(list_of_tensors_02):
      print("第{}个张量:{}, shape is {}".format(idx+1, t, t.shape))
      
      image.png
      list_of_tensors_03 = torch.split(t, [2, 1, 1], dim=1)
      for idx, t in enumerate(list_of_tensors_03):
         print("第{}个张量:{}, shape is {}".format(idx, t, t.shape))
      
      image.png

      NOTE:

      • 如果split_size_or_sections 是 list 时,list中的元素之和一定要等于 dim 上的长度

03. 张量索引

3.1 torch.index_select()

image.png

  • 功能:在维度dim上,按index索引数据
  • 返回值:依index索引数据拼接的张量

    • input: 要索引的张量
    • dim: 要索引的维度
    • index : 要索引数据的序号
      t = torch.randint(0, 9, size=(3, 3))
      idx = torch.tensor([0, 2], dtype=torch.long)    # float 类型会报错
      t_select = torch.index_select(t, dim=0, index=idx)
      print("t:\n{}\nt_select:\n{}".format(t, t_select))
      
  • 结果:

image.png

从一个3x3 的tensor中,dim=0,按行索引,索引值是[0, 2],只把第一行和第三行的值提取出来

3.2 torch.masked_select()

image.png

  • 功能:按 mask 中的 True 进行索引
  • 返回值:一维张量

    • input : 要索引的张量
    • mask : 与 input 同形状的布尔类型张量
      t = torch.randint(0, 9, size=(3, 3))
      mask = t.ge(5)  # >=5 的返回True. ge is `>=` ; gt is `>` / other parameters:le  lt
      t_select = torch.masked_select(t, mask)
      print("t:\n{}\nmask:\n{}\nt_select:\n{} ".format(t, mask, t_select))
      
  • 结果:

image.png

04. 张量变换

4.1 torch.reshape()

image.png

  • 功能:变换张量形状
    • input : 要变换的张量
    • shape : 新张量的形状

      NOTE:

      • 当张量在内存中是连续时,新张量与input共享数据内存
t = torch.randperm(8)
t_reshape = torch.reshape(t, (-1, 2, 2))    # -1
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))

t[0] = 1024
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))
print("t.data 内存地址:{}".format(id(t.data)))
print("t_reshape.data 内存地址:{}".format(id(t_reshape.data)))
  • 结果

image.png

4.2 torch.transpose()torch.t()

image.png

  • torch.transpose() 的功能:交换张量的两个维度
    • input : 要变换的张量
    • dim0 : 要交换的维度
    • dim1 : 要交换的维度
  • torch.t()的功能:2维张量转置。对矩阵而言,等价于 torch.transpose(input, 0, 1)

    t = torch.rand((2, 3, 4))
    t_transpose = torch.transpose(t, dim0=1, dim1=2)    # c*h*w     h*w*c
    print("t shape:{}\nt_transpose shape: {}".format(t.shape, t_transpose.shape))
    

    4.3 torch.squeeze()torch.unsqueeze()

    image.png

  • torch.squeeze() 功能:压缩长度为1的维度(轴)

    • dim: 若为None,移除所有长度为1的轴; 若指定维度,当且仅当该轴长度为1时,可以被移除;
  • torch.unsqueeze() 功能:依据 dim 扩展维度

    • dim : 扩展的维度
      t = torch.rand((1, 2, 3, 1))
      t_sq = torch.squeeze(t)
      t_0 = torch.squeeze(t, dim=0)
      t_1 = torch.squeeze(t, dim=1)
      t_2 = torch.unsqueeze(t, dim=2)
      print(t.shape)
      print(t_sq.shape)
      print(t_0.shape)
      print(t_1.shape)
      print(t_2.shape)
      
  • 结果

    torch.Size([1, 2, 3, 1])
    torch.Size([2, 3])
    torch.Size([2, 3, 1])
    torch.Size([1, 2, 3, 1])
    torch.Size([1, 2, 1, 3, 1])
    

    二、张量的数学运算

    image.png
    分为三大类:

  1. 加、减、乘、除
  2. 对数、指数、幂函数
  3. 三角函数

    torch.add()

    image.png
  • 功能:逐元素计算 input+alpha×other(在残差连接中有重要应用)
    • input : 第一个张量
    • alpha : 乘项因子
    • other : 第二个张量
  • 加法优化代码API

image.png

三、线性回归

线性回归是分析一个变量与另外一(多个)变量之间关系的方法。公式:y = wx + b
image.png

  • 因变量:y
  • 自变量:x
  • 关系:线性
  • 分析:求解 w,b

    01. 求解步骤

  1. 确定模型 : Model : y = wx + b
  2. 选择损失函数 : MSE(均方误差): 张量操作与线性回归 - 图20
  3. 求解梯度并且更新参数 w, b
    1. w = w - lr * w.grad
    2. b = b - lr * w.grad ```python

      -- coding: utf-8 --

      @Time : 2020/5/1 16:32

      @Author : DarrenZhang

      @FileName: linear regression.py

      @Software: PyCharm

      @Blog :https://www.yuque.com/darrenzhang

      @Brief : Linear Regression Model

      import torch import matplotlib.pyplot as plt torch.manual_seed(100)

lr = 0.001 # learning rate

create training data

x = torch.randn(20, 1) 10 print(x.shape) print(x.data) y = 2x + (5 + torch.randn(20, 1)) # y = wx + b + noise

build linear regression model

w = torch.randn(1, requires_grad=True) b = torch.zeros(1, requires_grad=True)

beginning to iterate

for iteration in range(10000):

# forward
wx = torch.mul(w, x)
y_pred = torch.add(wx, b)

# compute MSE loss
loss = (0.5 * (y - y_pred) ** 2).mean()

# backward
loss.backward()

# update parameters
b.data.sub_(lr * b.grad)  # b_update = b - lr * b.grad
w.data.sub_(lr * w.grad)

# clean grad to zero
w.grad.zero_()
b.grad.zero_()

# draw the process
if iteration % 100 == 0:
    plt.scatter(x.data.numpy(), y.data.numpy())
    plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
    plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color':  'red'})
    plt.xlim(1.5, 10)
    plt.ylim(8, 28)
    plt.title("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
    plt.pause(0.5)

    if loss.data.numpy() < 1:
        break

```