>>> t = torch.tensor([[1,1,1,1],[2,2,2,2],[3,3,3,3]], dtype= torch.float32)
>>>
>>> t
tensor([[1., 1., 1., 1.],
[2., 2., 2., 2.],
[3., 3., 3., 3.]])
>>> t.size()
torch.Size([3, 4])
>>> t.shape()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'torch.Size' object is not callable
>>> t.shape
torch.Size([3, 4])
>>>
>>>
>>> len(t.shape)
2
>>> torch.tensor(t.shape).prod()
tensor(12)
>>> t.numel()
12
>>> t
tensor([[1., 1., 1., 1.],
[2., 2., 2., 2.],
[3., 3., 3., 3.]])
>>> t.reshape(2,2,3)
tensor([[[1., 1., 1.],
[1., 2., 2.]],
[[2., 2., 3.],
[3., 3., 3.]]])
>>> t.shape
torch.Size([3, 4])
>>> t.size()
torch.Size([3, 4])
>>> t = t.reshape(2,2,3)
>>> t.shape
torch.Size([2, 2, 3])
>>> torch.tensor(t.shape).prod()
tensor(12)
>>> t.numel()
12
>>> t.reshape(1,12).squeeze()
tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
>>> t.reshape(1,12).squeeze().shape
torch.Size([12])
>>> t.reshape(1,12).squeeze()
tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
>>> t.reshape(1,12).squeeze().unsqueeze(dim=0)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]])



这段代码展示了如何在PyTorch中创建一个3x4的张量,并进行了尺寸查询、元素数量计算、张量重塑以及单轴挤压等操作。通过reshape、squeeze和unsqueeze等函数,理解张量形状变化对数据组织的影响。
1万+

被折叠的 条评论
为什么被折叠?



