Pytorch 张量

系统管理员 2023-07-24 05:45 34阅读 0赞

日萌社" class="reference-link">20191009191333910.png日萌社

人工智能AI:Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战(不定时更新)


Pytorch中数据-张量

目标

  1. 知道张量和Pytorch中的张量
  2. 知道pytorch中如何创建张量
  3. 知道pytorch中tensor的重要属性
  4. 知道pytorch中tensor的如何修改
  5. 知道pytorch中的cuda tensor
  6. 掌握pytorch中tensor的常用数学运算

1. 张量Tensor

张量是一个统称,其中包含很多类型:

  1. 0阶张量:标量、常数,0-D Tensor
  2. 1阶张量:向量,1-D Tensor
  3. 2阶张量:矩阵,2-D Tensor
  4. 3阶张量
  5. N阶张量

2. Pytorch中创建张量

  1. 从已有的数据中创建张量

    1. 从列表中创建

      torch.tensor([[1., -1.], [1., -1.]])
      tensor([[ 1.0000, -1.0000],

      1. [ 1.0000, -1.0000]])
    2. 使用numpy中的数组创建tensor

      torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
      tensor([[ 1, 2, 3],

      1. [ 4, 5, 6]])
  2. 创建固定张量

    1. torch.ones([3,4]) 创建3行4列的全为1的tensor
    2. torch.zeros([3,4])创建3行4列的全为0的tensor
    3. torch.ones_like(tensor) torch.zeros_like(tensor)创建与tensor相同形状和数据类型的值全为1/0的tensor
    4. torch.empty(3,4)创建3行4列的空的tensor,会用无用数据进行填充(手工填充torch.fill_)
  3. 在一定范围内创建序列张量

    1. torch.arange(start, end, step) 从start到end以step为步长取值生成序列
    2. torch.linspace(start, end, number_steps) 从start到end之间等差生成number_steps个数字组成序列
    3. torch.logspace(start, end, number_steps, base=10)20200409203409256.png之间等比生成number_steps个数字组成序列
  4. 创建随机张量

    1. torch.rand([3,4]) 创建3行4列的随机值的tensor,随机值的区间是[0, 1)

      1. >>> torch.rand(2, 3)
      2. tensor([[ 0.8237, 0.5781, 0.6879],
      3. [ 0.3816, 0.7249, 0.0998]])
    2. torch.randint(low=0,high=10,size=[3,4]) 创建3行4列的随机整数的tensor,随机值的区间是[low, high)

      1. >>> torch.randint(3, 10, (2, 2))
      2. tensor([[4, 5],
      3. [6, 7]])
    3. torch.randn([3,4]) 创建3行4列的随机数的tensor,随机值的分布式均值为0,方差为1

3. Pytorch中tensor的属性

  1. 获取tensor中的数据

    1. tensor.item() 当tensor中只有一个元素时

      In [10]: a = torch.tensor(np.arange(1))

      In [11]: a
      Out[11]: tensor([0])

      In [12]: a.item()
      Out[12]: 0

    2. 转化为numpy数组

      In [55]: z.numpy()
      Out[55]:
      array([[-2.5871205],

      1. [ 7.3690367],
      2. [-2.4918075]], dtype=float32)
  2. 获取形状:tensor.size() tensor.shape

    1. In [72]: x
    2. Out[72]:
    3. tensor([[ 1, 2],
    4. [ 3, 4],
    5. [ 5, 10]], dtype=torch.int32)
    6. In [73]: x.size()
    7. Out[73]: torch.Size([3, 2])
  3. 获取数据类型tensor.dtype

    1. In [80]: x.dtype
    2. Out[80]: torch.int32

    tensor中的数据类型非常多,常见类型如下:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ppbWlhbzU1MjE0NzU3Mg_size_16_color_FFFFFF_t_70

  1. 上图中的Tensor types表示这种type的tensor是其实例
  2. 获取阶数:tensor.dim()

    1. In [77]: x.dim()
    2. Out[77]: 2

4.tensor的修改

  1. 形状改变:

    1. tensor.view((3,4)) 类似numpy中的reshape

      In [76]: x.view(2,3)
      Out[76]:
      tensor([[ 1, 2, 3],

      1. [ 4, 5, 10]], dtype=torch.int32)
    2. tensor.t()tensor.transpose(dim0, dim1) 转置

      1. In [79]: x.t()
      2. Out[79]:
      3. tensor([[ 1, 3, 5],
      4. [ 2, 4, 10]], dtype=torch.int32)
    3. tensor.permute 变更tensor的轴(多轴转置)

      需求:把[4,2,3]转置成[3,4,2],如果使用transpose 需要转两次: [4,2,3] ->[4,3,2]->[3,4,2]

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ppbWlhbzU1MjE0NzU3Mg_size_16_color_FFFFFF_t_70 1

  1. In [61]: b1
  2. Out[61]:
  3. tensor([[[1., 2., 3.],
  4. [4., 5., 6.]],
  5. [[2., 2., 3.],
  6. [4., 5., 6.]],
  7. [[3., 2., 3.],
  8. [4., 5., 6.]],
  9. [[4., 2., 3.],
  10. [4., 5., 6.]]])
  11. In [62]: b1.size()
  12. Out[62]: torch.Size([4, 2, 3])
  13. In [63]: b2 = b1.transpose(1,2) # 把下标为1,和2的轴互换
  14. In [64]: b2
  15. Out[64]:
  16. tensor([[[1., 4.],
  17. [2., 5.],
  18. [3., 6.]],
  19. [[2., 4.],
  20. [2., 5.],
  21. [3., 6.]],
  22. [[3., 4.],
  23. [2., 5.],
  24. [3., 6.]],
  25. [[4., 4.],
  26. [2., 5.],
  27. [3., 6.]]])
  28. In [65]: b2.size()
  29. Out[65]: torch.Size([4, 3, 2])

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ppbWlhbzU1MjE0NzU3Mg_size_16_color_FFFFFF_t_70 2

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ppbWlhbzU1MjE0NzU3Mg_size_16_color_FFFFFF_t_70 3

  1. In [65]: b2.size()
  2. Out[65]: torch.Size([4, 3, 2])
  3. In [66]: b3 = b2.transpose(0,1)
  4. In [67]: b3
  5. Out[67]:
  6. tensor([[[1., 4.],
  7. [2., 4.],
  8. [3., 4.],
  9. [4., 4.]],
  10. [[2., 5.],
  11. [2., 5.],
  12. [2., 5.],
  13. [2., 5.]],
  14. [[3., 6.],
  15. [3., 6.],
  16. [3., 6.],
  17. [3., 6.]]])
  18. In [68]: b3.size()
  19. Out[68]: torch.Size([3, 4, 2])

如果使用permute,把[4,2,3]变成[3,4,2]只需要调用一次

  1. In [70]: b1.permute(2,0,1)
  2. Out[70]:
  3. tensor([[[1., 4.],
  4. [2., 4.],
  5. [3., 4.],
  6. [4., 4.]],
  7. [[2., 5.],
  8. [2., 5.],
  9. [2., 5.],
  10. [2., 5.]],
  11. [[3., 6.],
  12. [3., 6.],
  13. [3., 6.],
  14. [3., 6.]]])
  1. tensor.unsqueeze(dim) tensor.squeeze()填充或者压缩维度

    1. # tensor.squeeze() 默认去掉所有长度是1的维度,
    2. # 也可以填入维度的下标,指定去掉某个维度
    3. In [82]: a
    4. Out[82]:
    5. tensor([[[1],
    6. [2],
    7. [3]]])
    8. In [83]: a.size()
    9. Out[83]: torch.Size([1, 3, 1])
    10. In [84]: a.squeeze()
    11. Out[84]: tensor([1, 2, 3])
    12. In [85]: a.squeeze(0)
    13. Out[85]:
    14. tensor([[1],
    15. [2],
    16. [3]])
    17. In [86]: a.squeeze(2)
    18. Out[86]: tensor([[1, 2, 3]])
    19. In [87]:
    20. ## 如果需要扩充tensor的维度
    21. In [74]: a = torch.tensor([1,2,3])
    22. In [75]: a.size()
    23. Out[75]: torch.Size([3])
    24. In [76]: a.unsqueeze(0)
    25. Out[76]: tensor([[1, 2, 3]])
    26. In [77]: a.size()
    27. Out[77]: torch.Size([3])
    28. In [78]: a.unsqueeze(1) # [3,1]
    29. Out[78]:
    30. tensor([[1],
    31. [2],
    32. [3]])
  2. 类型的指定或修改

    1. 创建数据的时候指定类型

      1. In [88]: torch.ones([2,3],dtype=torch.float32)
      2. Out[88]:
      3. tensor([[1., 1., 1.],
      4. [1., 1., 1.]])
    2. 改变已有tensor的类型

      1. In [17]: a
      2. Out[17]: tensor([1, 2], dtype=torch.int32)
      3. In [18]: a.type(torch.float)
      4. Out[18]: tensor([1., 2.])
      5. In [19]: a.double()
      6. Out[19]: tensor([1., 2.], dtype=torch.float64)
  3. tensor的切片

    1. In [101]: x
    2. Out[101]:
    3. tensor([[1.6437, 1.9439, 1.5393],
    4. [1.3491, 1.9575, 1.0552],
    5. [1.5106, 1.0123, 1.0961],
    6. [1.4382, 1.5939, 1.5012],
    7. [1.5267, 1.4858, 1.4007]])
    8. In [102]: x[:,1]
    9. Out[102]: tensor([1.9439, 1.9575, 1.0123, 1.5939, 1.4858])
  4. 切片赋值

    1. In [12]: x[:, 1]
    2. Out[12]: tensor([1.9439, 1.9575, 1.0123, 1.5939, 1.4858])
    3. In [13]: x[:, 1] = 1
    4. In [14]: x[:, 1]
    5. Out[14]: tensor([1., 1., 1., 1., 1.])

注意:切片数据内存不连续

  1. In [87]: a = torch.randn(2,3,4)
  2. In [88]: a
  3. Out[88]:
  4. tensor([[[ 0.6204, 0.9294, 0.6449, -2.0183],
  5. [-1.1809, 0.4071, -1.0827, 1.7154],
  6. [ 0.0431, 0.6646, 2.0386, 0.0777]],
  7. [[ 0.0052, -0.1531, -0.7470, -0.8283],
  8. [-0.1547, 0.3123, -0.6279, -0.0132],
  9. [-0.0527, -1.2305, 0.7089, -0.4231]]])
  10. In [89]: a[:,:1,:2]
  11. Out[89]:
  12. tensor([[[ 0.6204, 0.9294]],
  13. [[ 0.0052, -0.1531]]])
  14. In [90]: a[:,:1,:2].view(1,4)
  15. ---------------------------------------------------------------------------
  16. RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
  17. In [91]: a[:,:1,:2].reshape(1,4)
  18. Out[91]: tensor([[ 0.6204, 0.9294, 0.0052, -0.1531]])

5. CUDA Tensor

  1. 什么是CUDA?

    CUDA(Compute Unified Device Architecture):CUDA™是一种由NVIDIA推出的通用并行计算架构,该架构使GPU能够解决复杂的计算问题(GPU,或者叫做显卡,如果没有cuda这个框架,就只能完成图形渲染)。

  2. 如何使pytorch能够调用cuda框架(使用gpu完成深度学习计算)?

    ​1.本机需要有一个NVIDIA的gpu

    ​2.本机需要安装一个适配的gpu驱动

    ​3.本机需要安装一个与该gpu适配的CUDA框架

    ​4.在python环境中安装gpu版本pytorch

  3. 如何判断当前环境中的pytorch能否调用cuda框架进行计算?

    torch.cuda这个模块增加了对CUDA tensor的支持,能够在cpu和gpu上使用相同的方法操作tensor

    torch.cuda.is_available()

  4. 如何把cpu tensor转换成 cuda tensor

    通过.to方法能够把一个tensor转移到另外一个设备(比如从CPU转到GPU)

    device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)

    if torch.cuda.is_available():

    1. device = torch.device("cuda") # cuda device对象
    2. y = torch.ones_like(x, device=device) # 创建一个在cuda上的tensor
    3. x = x.to(device) # 使用方法把x转为cuda的tensor
    4. z = x + y
    5. print(z)
    6. print(z.to("cpu", torch.double)) # .to方法也能够同时设置类型

    tensor([1.9806], device=’cuda:0’)
    tensor([1.9806], dtype=torch.float64)

6. tensor的常用数学运算

  1. tensor.add tensor.sub tensor.abs tensor.mm

    1. In [204]: a = torch.tensor([1,2,3])
    2. In [205]: b = torch.tensor(1)
    3. In [206]: a.add(b)
    4. Out[206]: tensor([2, 3, 4])
    5. In [207]: a.sub(b)
    6. Out[207]: tensor([0, 1, 2])
    7. In [212]: c = torch.randn((3,))
    8. In [213]: c
    9. Out[213]: tensor([ 0.5161, -0.1732, 1.0162])
    10. In [214]: c.abs()
    11. Out[214]: tensor([0.5161, 0.1732, 1.0162])
    12. In [215]: c
    13. Out[215]: tensor([ 0.5161, -0.1732, 1.0162])
    14. In [254]: a = torch.randn([3,4])
    15. In [255]: b = torch.randn([4, 5])
    16. In [256]: a.mm(b)
    17. Out[256]:
    18. tensor([[ 0.6888, 0.4304, -0.5489, 0.3615, -1.1690],
    19. [ 1.0890, -1.0391, -0.3717, -0.4045, 3.4404],
    20. [ 0.9885, 0.1720, -0.2117, -0.1694, -0.5460]])

    注意:tensor之间元素级别的数学运算同样适用广播机制。

    1. In [145]: a = torch.tensor([[1,2], [3,4]])
    2. In [146]: b = torch.tensor([1,2])
    3. In [147]: a + b
    4. Out[147]:
    5. tensor([[2, 4],
    6. [4, 6]])
    7. In [148]: c = torch.tensor([[1,],[2]])
    8. In [149]: a + c
    9. Out[149]:
    10. tensor([[2, 3],
    11. [5, 6]])
  2. 简单函数运算 torch.exp torch.sin torch.cos

    1. In [109]: torch.exp(torch.tensor([0, np.log(2)]))
    2. Out[109]: tensor([1., 2.])
    3. In [110]: torch.tensor([0, np.log(2)]).exp()
    4. Out[110]: tensor([1., 2.])
    5. In [111]: torch.sin(torch.tensor([0, np.pi]))
    6. Out[111]: tensor([ 0.0000e+00, -8.7423e-08])
    7. In [112]: torch.cos(torch.tensor([0, np.pi]))
    8. Out[112]: tensor([ 1., -1.])
  3. in-place 原地操作 tensor.add_ tensor.sub_ tensor.abs_

    1. In [224]: a
    2. Out[224]: tensor([1, 2, 3])
    3. In [225]: b
    4. Out[225]: tensor(1)
    5. In [226]: a.add(b)
    6. Out[226]: tensor([2, 3, 4])
    7. In [227]: a
    8. Out[227]: tensor([1, 2, 3])
    9. In [228]: a.add_(b)
    10. Out[228]: tensor([2, 3, 4])
    11. In [229]: a
    12. Out[229]: tensor([2, 3, 4])
    13. In [236]: c.abs()
    14. Out[236]: tensor([0.5161, 0.1732, 1.0162])
    15. In [237]: c
    16. Out[237]: tensor([ 0.5161, -0.1732, 1.0162])
    17. In [238]: c.abs_()
    18. Out[238]: tensor([0.5161, 0.1732, 1.0162])
    19. In [239]: c
    20. Out[239]: tensor([0.5161, 0.1732, 1.0162])
    21. In [240]: c.zero_()
    22. Out[240]: tensor([0., 0., 0.])
    23. In [241]: c
    24. Out[241]: tensor([0., 0., 0.])
  4. 统计操作 tensor.max, tensor.min, tensor.mean,tensor.median tensor.argmax

    In [242]: a
    Out[242]: tensor([ 0.5161, -0.1732, 1.0162])

    In [243]: a.max()
    Out[243]: tensor(1.0162)

    In [246]: a
    Out[246]:
    tensor([[ 0.3337, -0.5011, -1.4319, -0.6633],

    1. [ 0.6620, 1.3154, -0.9129, 0.4685],
    2. [ 0.3203, -1.6496, 1.1967, -0.3174]])

    In [247]: a.max()
    Out[247]: tensor(1.3154)

    In [248]: a.max(dim=0)
    Out[248]:
    torch.return_types.max(
    values=tensor([0.6620, 1.3154, 1.1967, 0.4685]),
    indices=tensor([1, 1, 2, 1]))

    In [249]: a.max(dim=0)[0]
    Out[249]: tensor([0.6620, 1.3154, 1.1967, 0.4685])

    In [250]: a.max(dim=0)[1]
    Out[250]: tensor([1, 1, 2, 1])

    In [251]: a.argmax()
    Out[251]: tensor(5)

    In [252]: a.argmax(dim=0)
    Out[252]: tensor([1, 1, 2, 1])

通过前面的学习,可以发现torch的各种操作几乎和numpy一样

更多tensor的操作,参考 https://pytorch.org/docs/stable/tensors.html

7 Variable

在一些旧版本中的pytorch代码中,还可能会见到一个Variable类(from torch.autograd import Variable),基本上和tensor的用法是一样的。

发表评论

表情:
评论列表 (有 0 条评论,34人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PyTorch (笔记)

    1. 张量简介 在深度学习中,我们通常将数据以张量的形式进行表示。几何代数中定义的张量是基于向量和矩阵的推广,比如我们可以将标量视为零阶张量,矢量视为一阶张量,矩阵就是二