深度学习PyTorch笔记(2):Tensor的算术操作

  • 这是《动手学深度学习》(PyTorch版)(Dive-into-DL-PyTorch)的学习笔记,里面有一些代码是我自己拓展的。

    其他笔记在专栏 深度学习 中。


    1.2.1 算术操作

    加减乘除、求余、求幂、指数、绝对值:

    #可以是两个张量,也可以是张量和数字
    x = torch.tensor([1, 2, 4])
    y = torch.tensor([2, 1, 2])
    print(x + y, torch.add(x, y), x.add(y))
    print(x - y)
    print(torch.abs(x - y))  #绝对值
    print(x * y, torch.mul(x, y), x.mul(y))
    print(x / y, torch.div(x, y), x.div(y))
    print(x % y) 
    print(x ** y, torch.pow(x, y), x.pow(y))
    print(torch.exp(x))
    
    tensor([3, 3, 6]) tensor([3, 3, 6]) tensor([3, 3, 6])
    tensor([-1,  1,  2])
    tensor([1, 1, 2])
    tensor([2, 2, 8]) tensor([2, 2, 8]) tensor([2, 2, 8])
    tensor([0.5000, 2.0000, 2.0000]) tensor([0.5000, 2.0000, 2.0000]) tensor([0.5000, 2.0000, 2.0000])
    tensor([1, 0, 0])
    tensor([ 1,  2, 16]) tensor([ 1,  2, 16]) tensor([ 1,  2, 16])
    tensor([ 2.7183,  7.3891, 54.5981]))
    


    多种加法:

    x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    y = torch.tensor([[3, 2, 1], [6, 5, 4], [9, 8, 7]])
    
    print(x + y)
    
    print(torch.add(x, y))
    
    result = torch.empty(3, 3)
    torch.add(x, y, out=result) #把x+y放入创建的空tensor中
    print(result)
    print(result.type())
    
    y.add_(x)  #上面的一种变式,注意有一个‘_’,这个符号在所有替换自身操作符的末尾都有,另外,输出的方式还可以象python一样。
    print(y)
    print(y.type())
    
    tensor([[ 4,  4,  4],
            [10, 10, 10],
            [16, 16, 16]])
    tensor([[ 4,  4,  4],
            [10, 10, 10],
            [16, 16, 16]])
    tensor([[ 4.,  4.,  4.],
            [10., 10., 10.],
            [16., 16., 16.]])
    torch.FloatTensor
    tensor([[ 4,  4,  4],
            [10, 10, 10],
            [16, 16, 16]])
    torch.LongTensor
    

    注意出现的结果的类型!第三个结果的类型是浮点型。

    #矩阵乘法
    x = torch.tensor([[1, 2]])  #要确保是矩阵
    y = torch.tensor([[3], [4]])
    torch.mm(x, y), x.mm(y)  #1*3+2*4
    
    >>> (tensor([[11]]), tensor([[11]]))
    
    #矩阵乘向量
    x = torch.tensor([[1,2,3], 
                      [4,5,6]])
    y = torch.tensor([1,2,3])  #列向量
    torch.mv(x, y), x.mv(y)  #就和矩阵相乘的方式一样
    
    >>> (tensor([14, 32]), tensor([14, 32]))