view()和reshape()比较

2022-07-30  本文已影响0人  LabVIEW_Python

PyTorch Tensor自带的方法view()和reshape():

使用下来,都是作用都是更改Tensor的Shape,而且性能没啥差别 view vs reshape

但是,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))

总结:优先选用reshape, 而不是view

上一篇 下一篇

猜你喜欢

热点阅读