PyTorch Tensor自带的方法view()和reshape():
- view(): Returns a new tensor with the same data as the self tensor but of a different shape.
- reshape(): Returns a tensor with the same data and number of elements as self but with the specified shape.

但是,view要求tensor元素连续,若不连续,则推荐用reshape
Traceback (most recent call last):
File "d:/pytorch/tensor_reshape.py", line 9, in <module>
print(y.view(9))
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.
import torch
x_3x3 = torch.arange(9).reshape(3,3)
print(x_3x3)
# Transpose
y = x_3x3.t()
print(y)
# view size is not compatible with input tensor's size and stride (at least one dimension
# spans across two contiguous subspaces). Use .reshape(...) instead
# print(y.view(9))
print(y.reshape(9))
网友评论