【机器学习】Pytorch常用的方法

目录

    • arrange
    • permute
    • range
    • repeat
    • tensor

arrange

torch.arange(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

返回一个元素个数为(end-start)/step,维度是1*D的tensor。元素里面不包含end

permute

permute(*dims) → Tensor

对任意高维矩阵进行转置。

>>> x = torch.randn(2,3,5)
>>> x.size()
torch.Size([2, 3, 5])
>>> x
tensor([[[-0.5745,  1.1764,  0.7518,  0.9021,  2.4685],
         [ 1.2288, -0.1018,  1.2049, -0.1429,  1.2599],
         [ 1.9483, -0.6745,  0.9937, -0.0432, -1.2532]],

        [[ 0.7589,  0.6292, -0.2349, -1.0436,  0.4462],
         [-0.3739,  0.9542,  0.4136, -0.8185,  1.0435],
         [-1.8790, -0.4924, -0.5502, -2.4309,  1.0902]]])
>>> x.permute(2,0,1)
tensor([[[-0.5745,  1.2288,  1.9483],
         [ 0.7589, -0.3739, -1.8790]],

        [[ 1.1764, -0.1018, -0.6745],
         [ 0.6292,  0.9542, -0.4924]],

        [[ 0.7518,  1.2049,  0.9937],
         [-0.2349,  0.4136, -0.5502]],

        [[ 0.9021, -0.1429, -0.0432],
         [-1.0436, -0.8185, -2.4309]],

        [[ 2.4685,  1.2599, -1.2532],
         [ 0.4462,  1.0435,  1.0902]]])
>>> x.permute(2,0,1).size()
torch.Size([5, 2, 3])

注意:
1、没有torch.permute这样的用法。
2、不会修改x自身。

range

torch.range(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

返回一个元素个数为(end-start)/step,维度是1*D的tensor。元素里面包含end

repeat

repeat(*sizes) → Tensor

根据特定维度复制扩展Tensor

>>> x=torch.tensor([1, 2, 3])
>>> x.repeat(4, 2)
tensor([[1, 2, 3, 1, 2, 3],
        [1, 2, 3, 1, 2, 3],
        [1, 2, 3, 1, 2, 3],
        [1, 2, 3, 1, 2, 3]])
>>> x.repeat(4, 2, 1)
tensor([[[1, 2, 3],
         [1, 2, 3]],

        [[1, 2, 3],
         [1, 2, 3]],

        [[1, 2, 3],
         [1, 2, 3]],

        [[1, 2, 3],
         [1, 2, 3]]])

tensor

torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor

使用data构建一个tensor

>>> import torch
>>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
tensor([[0.1000, 1.2000],
        [2.2000, 3.1000],
        [4.9000, 5.2000]])
>>> torch.tensor([[0.11111, 0.222222, 0.3333333]]).shape
torch.Size([1, 3])
>>> torch.tensor(3.14159) #0维Tensor
tensor(3.1416)

你可能感兴趣的:(机器学习,机器学习,pytorch,python)