这些完全一样吗?
myTensor.contiguous().flatten()
myTensor.view(-1)他们会返回相同的自动梯度功能等吗?
发布于 2021-04-22 14:08:35
不,它们不完全一样。
myTensor.contiguous().flatten()在这里,contiguous()要么返回存储在连续内存中的myTensor副本,要么返回myTensor本身(如果它已经是连续的)。然后,flatten()将张量重塑为一个一维。但是,返回的张量可能是与myTensor、视图或副本相同的对象,因此不能保证输出的连续性。
相关文档
还值得一提的是一些具有特殊行为的操作:
myTensor.view(-1)在这里,view()返回一个与myTensor相同数据的张量,并且只有在myTensor已经是连续的情况下才能工作。结果可能不是毗连的取决于myTensor的形状。
发布于 2021-04-22 14:16:48
一些例子:
xxx = torch.tensor([[1], [2], [3]])
xxx = xxx.expand(3, 4)
print ( xxx )
print ( xxx.contiguous().flatten() )
print ( xxx.view(-1) )
tensor([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
tensor([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-7-281fe94f55fb> in <module>
3 print ( xxx )
4 print ( xxx.contiguous().flatten() )
----> 5 print ( xxx.view(-1) )
RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.https://stackoverflow.com/questions/67214586
复制相似问题