What is the difference between x.view(x.size(0), -1) and torch.nn.Flatten() layer and torch.flatten(x)? pytorch question
I'm quite curious on what's the difference between using view(,-1) and flatten like the simple code here:
Since I found that the size and data all flatten to one dimension.
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())

And also, it seems there is no difference between = and =.contiguous which said :Returns a contiguous in memory tensor containing the same data as self tensor. but for me, it seems just return the self tensor but not copy or new tensor with same data.
c = y
print(c)
b = y.contiguous()
print(b)

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


A view is a way to modify the way you look at your data without modifying the data itself:

torch.view returns a view on the data: the data is not copied, only the &quot;window&quot; which you look through on the data changes
torch.flatten returns a one-dimensional output from a multi-dimensional input. It may not copy the data if


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


torch.nn.Flatten is just a wrapper for convenience around torch.flatten

Contiugous data just means that the data is linearly adressable in memory, e.g. for two dimension data this would mean that element [i][j] is at position i * num_columns + j. If this is already the case then .contiguous will not change your data or copy anything.
