What is the difference between .flatten() and .view(-1) in PyTorch?(PyTorch 中的 .flatten() 和 .view(-1) 有什么区别?)
问题描述
.flatten() 和 .view(-1) 都在 PyTorch 中展平张量.有什么区别?
Both .flatten() and .view(-1) flatten a tensor in PyTorch. What's the difference?
.flatten()会复制张量的数据吗?.view(-1)是否更快?- 是否存在
.flatten()不起作用的情况?
- Does
.flatten()copy the data of the tensor? - Is
.view(-1)faster? - Is there any situation that
.flatten()doesn't work?
推荐答案
除了@adeelh 的注释,还有一个区别:torch.flatten() 导致 .reshape(),以及 .reshape() 和 .view() 之间的区别 是:
In addition to @adeelh's comment, there is another difference: torch.flatten() results in a .reshape(), and the differences between .reshape() and .view() are:
[...]
torch.reshape可能会返回原始张量的副本或视图.您不能指望它返回视图或副本.
[...]
torch.reshapemay return a copy or a view of the original tensor. You can not count on that to return a view or a copy.
另一个区别是 reshape() 可以对连续和非连续张量进行操作,而 view() 只能对连续张量进行操作.另请参阅此处有关连续的含义
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功能,之后 问题 #7743,该功能已在 PR #8578.
The community requested for a
flattenfunction for a while, and after Issue #7743, the feature was implemented in the PR #8578.
可以看到flatten的实现这里,在 return 行中可以看到对 .reshape() 的调用.
You can see the implementation of flatten here, where a call to .reshape() can be seen in return line.
这篇关于PyTorch 中的 .flatten() 和 .view(-1) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PyTorch 中的 .flatten() 和 .view(-1) 有什么区别?
基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
