如何用pytorch深度学习第二章——基本运算操作1

77 阅读1分钟

这里讲的是用torch来如何运用基本运算操作
废话不多说 上代码

  1. 导入PyTorch库

    import torch
    
  2. torch.randint函数生成随机整数张量

    a = torch.randint(1, 5, (2, 3))
    b = torch.randint(1, 5, (2, 3))
    

    这里使用torch.randint函数生成两个随机整数张量abtorch.randint的第一个参数是随机数的最小值,第二个参数是最大值(不包含),第三个参数是张量的形状。所以这里生成的是两个2x3的张量,其中的元素是1到4之间的随机整数。

  3. 打印张量a和b

    print("a的输出:\n", a)
    print("b的输出:\n", b)
    
    执行a的输出:
     tensor([[3, 2, 2],
         [3, 1, 4]])
    执行b的输出:
     tensor([[1, 2, 4],
         [2, 1, 4]])
    
    

    这两行代码打印出张量ab的内容。

  4. 张量相加

    c = torch.add(a, b)
    print("c的输出:\n", c)
    执行c的输出:
    tensor([[4, 4, 6],
         [5, 2, 8]])
    

    这里使用torch.add函数将张量ab相加,得到新的张量c

  5. 创建3x5的全1张量

    tensor = torch.ones(3, 5)
    print("tensor的输出:\n", tensor)
    tensor的输出:
    tensor([[1., 1., 1., 1., 1.],
         [1., 1., 1., 1., 1.],
         [1., 1., 1., 1., 1.]])
    

    这里使用torch.ones函数创建一个3x5的全1张量。

  6. 矩阵乘法

    a = a.float()
    d = torch.matmul(a, tensor)
    print("d的输出:\n", d)
    d的输出:
     tensor([[7., 7., 7., 7., 7.],
         [8., 8., 8., 8., 8.]])
    

    这里首先将张量a转换为浮点数类型(因为torch.matmul要求参与运算的张量必须是浮点数类型),然后使用torch.matmul函数进行矩阵乘法运算,得到新的张量d