【发布时间】:2019-11-13 08:51:27
【问题描述】:
我是 pytorch 的新手。在玩张量时,我观察到了两种类型的张量-
tensor(58)
tensor([57.3895])
我打印了它们的形状,输出分别是-
torch.Size([])
torch.Size([1])
两者有什么区别?
【问题讨论】:
我是 pytorch 的新手。在玩张量时,我观察到了两种类型的张量-
tensor(58)
tensor([57.3895])
我打印了它们的形状,输出分别是-
torch.Size([])
torch.Size([1])
两者有什么区别?
【问题讨论】:
【讨论】:
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)).
您可以像这样使用具有单个标量值的张量:
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。
【讨论】:
在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 的张量。
【讨论】: