【问题标题】:Difference in shape of tensor torch.Size([]) and torch.Size([1]) in pytorchpytorch中张量torch.Size([])和torch.Size([1])的形状差异
【发布时间】:2019-11-13 08:51:27
【问题描述】:

我是 pytorch 的新手。在玩张量时,我观察到了两种类型的张量-

tensor(58)
tensor([57.3895])

我打印了它们的形状,输出分别是-

torch.Size([])
torch.Size([1])

两者有什么区别?

【问题讨论】:

    标签: pytorch tensor


    【解决方案1】:

    第一个有0 size 尺寸,第二个有1 尺寸,PyTorch 试图使两者兼容(0 size 可以被视为类似于float 或类似虽然我还没有真正遇到过明确需要它的情况,除了@javadr 在下面的答案中显示的内容)。

    通常你会使用list 来初始化它,see here 以获取更多信息。

    【讨论】:

    • 我认为这并没有错,它的意思是一个维度为0的张量。
    • 查看fill_。它只需要一个 0 维值张量。所以,你不能像t.fill_(torch.tensor([1])) 那样使用它。它完全错误并产生以下错误:RuntimeError: fill_ only supports 0-dimension value tensor but got tensor with 1 dimensions. 但它适用于如下使用:t.fill_(torch.tensor(1)).
    【解决方案2】:

    您可以像这样使用具有单个标量值的张量:

    import torch
    
    t = torch.tensor(1)
    print(t, t.shape) # tensor(1) torch.Size([])
    
    t = torch.tensor([1])
    print(t, t.shape) # tensor([1]) torch.Size([1])
    
    t = torch.tensor([[1]])
    print(t, t.shape) # tensor([[1]]) torch.Size([1, 1])
    
    t = torch.tensor([[[1]]])
    print(t, t.shape) # tensor([[[1]]]) torch.Size([1, 1, 1])
    
    t = torch.unsqueeze(t, 0)
    print(t, t.shape) # tensor([[[[1]]]]) torch.Size([1, 1, 1, 1])
    
    t = torch.unsqueeze(t, 0)
    print(t, t.shape) # tensor([[[[[1]]]]]) torch.Size([1, 1, 1, 1, 1])
    
    t = torch.unsqueeze(t, 0)
    print(t, t.shape) # tensor([[[[[[1]]]]]]) torch.Size([1, 1, 1, 1, 1, 1])
    
    #squize dimension with id 0
    t = torch.squeeze(t,dim=0)
    print(t, t.shape) # tensor([[[[[1]]]]]) torch.Size([1, 1, 1, 1, 1])
    
    #back to beginning.
    t = torch.squeeze(t)
    print(t, t.shape) # tensor(1) torch.Size([])
    
    print(type(t)) # <class 'torch.Tensor'>
    print(type(t.data)) # <class 'torch.Tensor'>
    

    张量,确实有大小或形状。这是一样的。这实际上是一个类torch.Size。 您可以写信help(torch.Size) 以获取更多信息。 任何时候你写t.shape,或t.size(),你都会得到那个尺寸信息。

    张量的想法是它们可以为其中的数据具有不同的兼容大小维度,包括torch.Size([])

    任何时候你解压一个张量,它都会增加另一个维度 1。 任何时候你挤压一个张量,它都会删除 1 的维度,或者在一般情况下,所有的维度都是 1。

    【讨论】:

      【解决方案3】:

      pytorch中查看tensor的文档:

      Docstring:
      tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor
      
      Constructs a tensor with :attr:`data`.
      

      然后它描述了数据是什么:

      Args:
          data (array_like): Initial data for the tensor. Can be a list, tuple,
              NumPy ``ndarray``, scalar, and other types.
      

      如您所见,data 可能是一个标量(它是一个维数为零的数据)。

      因此,在回答您的问题时,tensor(58) 是尺寸为 0 的张量,tensor([58]) 是尺寸为 1 的张量。

      【讨论】:

        猜你喜欢
        • 2021-05-10
        • 2021-06-27
        • 1970-01-01
        • 2021-12-05
        • 2020-01-07
        • 2021-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多