x.view(x.size(0), -1) 和 torch.nn.Flatten() 层和 torch.flatten(x) 有什么区别?火炬问题

What is the difference between x.view(x.size(0), -1) and torch.nn.Flatten() layer and torch.flatten(x)? pytorch question

我很好奇使用 view(,-1) 和像这里的简单代码一样展平有什么区别:

因为我发现大小和数据都扁平化到一维了

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt

x = torch.rand(3,256,256)
x.size()

a = x.view(x.size(0), -1)
print('after view:',a.size())

m = nn.Sequential(nn.Flatten())
y = m(x)
print('after nn flatten:',y.size())
z = torch.flatten(x)
print('after torch flatten:',y.size())

而且,= 和 =.contiguous 之间似乎没有区别,后者表示:Returns 内存中的连续张量包含与自身张量相同的数据。但对我来说,它似乎只是 return 自张量而不是具有相同数据的副本或新张量。

c = y
print(c)
b = y.contiguous()
print(b)

# change original data
y[0][0]=1
print(b)
print(c)
print(y)

视图是一种在不修改数据本身的情况下修改您查看数据的方式的方法:

  • torch.view returns 对数据的看法:数据没有被复制,只有你查看数据的“window”发生变化
  • torch.flatten returns 多维输入的一维输出。如果
  • ,它可能不会复制数据

[the] input can be viewed as the flattened shape (source)

  • torch.nn.Flatten 只是 wrapper 为了方便 torch.flatten

连续数据只是意味着数据在内存中是线性可寻址的,例如对于二维数据,这意味着元素 [i][j] 位于位置 i * num_columns + j。如果已经是这种情况,那么 .contiguous 将不会更改您的数据或复制任何内容。