我是pytorch的新手。在玩弄张量时,我观察到两种类型的张量:
tensor(58)
tensor([57.3895])
我打印了它们的形状,输出分别为 -
torch.Size([])
torch.Size([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'>
help(torch.Size)
以获取更多信息。每当您编写t.shape
或t.size()
时,都将获得该大小信息。torch.Size([])
。请查看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)
是一个零维张量,而 tensor([58])
则是一个一维张量。
0
的张量。 - javadrfill_
。它只接受一个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))
。 - javadr