python - .data 在 pytorch 中仍然有用吗?

标签 python version pytorch tensor

我是 pytorch 的新手。我读了很多大量使用张量的 .data 成员的 pytorch 代码。但是我在官方文档和谷歌中搜索.data,一无所获。我猜 .data 包含张量中的数据,但我不知道我们什么时候需要它,什么时候不需要?

最佳答案

.dataVariable 的属性(代表 Tensor 的对象,具有历史跟踪功能,例如用于自动更新),而不是 Tensor。实际上,.data 允许访问 Variable 的底层 Tensor

但是,自 PyTorch 版本 0.4.0 以来,VariableTensor 已合并(成为更新的 Tensor 结构),因此 .data 沿着之前的 Variable 对象消失了(Variable 仍然存在是为了向后兼容,但已弃用)。


段落自Release Notes对于 0.4.0 版本(我建议阅读有关 Variable/Tensor 更新的整个部分):

What about .data?

.data was the primary way to get the underlying Tensor from a Variable. After this merge, calling y = x.data still has similar semantics. So y will be a Tensor that shares the same data with x, is unrelated with the computation history of x, and has requires_grad=False.

However, .data can be unsafe in some cases. Any changes on x.data wouldn't be tracked by autograd, and the computed gradients would be incorrect if x is needed in a backward pass. A safer alternative is to use x.detach(), which also returns a Tensor that shares data with requires_grad=False, but will have its in-place changes reported by autograd if x is needed in backward.

关于python - .data 在 pytorch 中仍然有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51743214/

相关文章:

Python:检查维基百科文章是否存在

android - 我可以允许用户卸载我的 Android 应用程序的更新吗?

python - 安装旧版本 python 时保留当前版本

macos - 更新 Homebrew 桶版本

python - 实现多对多回归任务

swift - 将 pytorch 转换为 torchscript 后的不同结果?将 NSnumber 转换为 Float 会造成任何损失吗?

python - Pandas 数据框条件 .mean() 取决于特定列中的值

python - 使用 updateCells API 请求更新多个单元格的格式

python - 在 PyTorch 中,grad_fn 属性究竟存储了什么以及它是如何使用的?

Python用反斜杠替换正斜杠