python - PyTorch 中的 .flatten() 和 .view(-1) 有什么区别?

标签 python pytorch

.flatten().view(-1) 都在 PyTorch 中展平张量。有什么区别?

  1. .flatten()是否复制张量的数据?
  2. .view(-1) 更快吗?
  3. 是否存在 .flatten() 不起作用的情况?

最佳答案

除了@adeelh 的评论之外,还有另一个区别:torch.flatten() 导致 .reshape(),而 differences between .reshape() and .view()是:

  • [...] torch.reshape may return a copy or a view of the original tensor. You can not count on that to return a view or a copy.

  • Another difference is that reshape() can operate on both contiguous and non-contiguous tensor while view() can only operate on contiguous tensor. Also see here about the meaning of contiguous

对于上下文:

  • 社区在一段时间内请求flatten 功能,在Issue #7743 之后,该功能已在 PR #8578 中实现.

  • 可以看到flatten的实现here ,其中可以在 return 行中看到对 .reshape() 的调用。

关于python - PyTorch 中的 .flatten() 和 .view(-1) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57234095/

相关文章:

python - 递归 os.listdir?

python - 谷歌应用程序引擎上的任务队列或多线程

Pythonic 方式链接 python 生成器函数以形成管道

python - 无法导入名称 SummaryWriter

python - 将 pytorch 数据加载器加载到 GPU

python - 如何将分页器 block 移动到页脚?

python - 如何修复数据集以返回所需的输出(pytorch)

c++ - PyTorch C++ 前端向前返回多个张量

python - 将pytorch中的roi池化转换为nn层

python - 如何在 __init__.py 中将包模块导入为 __main__ 别名?