RuntimeError: view size is not compatible with input tensor‘s size and stride

870 阅读1分钟

RuntimeError: view size is not compatible with input tensor‘s size and stride

在运行程序中:

def forward(self, x):
    out = self.cnn(x)
    out = out.view(out.size()[0], -1)
    return self.fc(out)

python报错:

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.

这是因为view()需要Tensor中的元素地址是连续的,但可能出现Tensor不连续的情况,所以先用 .contiguous() 将其在内存中变成连续分布:

out = out.contiguous().view(out.size()[0], -1)

这样就好了。