.contiguous().flatten() 和 PyTorch 中的 .view(-1) 一样吗?



这些完全一样吗?

myTensor.contiguous().flatten()
myTensor.view(-1)

他们会返回相同的自动渐变函数等吗?

不,它们不完全相同。

  • myTensor.contiguous().flatten()

在这里,contiguous()要么返回存储在连续内存中的myTensor的副本,要么返回myTensor本身(如果它已经是连续的)。然后,flatten()将张量重塑为单个维度。但是,返回的张量可以是与myTensor、视图或副本相同的对象,因此不能保证输出的连续性。

相关文档:

还值得一提的是一些具有特殊行为的操作:

  • reShape(),reshape_as()和flatten()可以返回视图或新张量,用户代码不应该依赖于它是否是视图。

  • 如果输入张量已经连续,则 contiguous() 返回自身,否则它通过复制数据返回一个新的连续张量。

  • myTensor.view(-1)

在这里,view()返回一个与myTensor具有相同数据的张量,并且只有在myTensor已经连续时才起作用。根据myTensor的形状,结果可能不连续。

一些插图:

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.

相关内容

最新更新