美文网首页
view()和reshape()比较

view()和reshape()比较

作者: LabVIEW_Python | 来源:发表于2022-07-30 15:14 被阅读0次

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.
使用下来,都是作用都是更改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

相关文章

网友评论

      本文标题:view()和reshape()比较

      本文链接:https://www.haomeiwen.com/subject/nuzcwrtx.html