我是 pytorch 的新手。我读了很多大量使用张量的 .data
成员的 pytorch 代码。但是我在官方文档和谷歌中搜索.data
,一无所获。我猜 .data
包含张量中的数据,但我不知道我们什么时候需要它,什么时候不需要?
最佳答案
.data
是 Variable
的属性(代表 Tensor
的对象,具有历史跟踪功能,例如用于自动更新),而不是 Tensor
。实际上,.data
允许访问 Variable
的底层 Tensor
。
但是,自 PyTorch 版本 0.4.0
以来,Variable
和 Tensor
已合并(成为更新的 Tensor
结构),因此 .data
沿着之前的 Variable
对象消失了(Variable
仍然存在是为了向后兼容,但已弃用)。
段落自Release Notes对于 0.4.0
版本(我建议阅读有关 Variable
/Tensor
更新的整个部分):
What about
.data
?
.data
was the primary way to get the underlyingTensor
from aVariable
. After this merge, callingy = x.data
still has similar semantics. Soy
will be aTensor
that shares the same data withx
, is unrelated with the computation history ofx
, and hasrequires_grad=False
.However,
.data
can be unsafe in some cases. Any changes onx.data
wouldn't be tracked byautograd
, and the computed gradients would be incorrect ifx
is needed in a backward pass. A safer alternative is to usex.detach()
, which also returns aTensor
that shares data withrequires_grad=False
, but will have its in-place changes reported byautograd
ifx
is needed in backward.
关于python - .data 在 pytorch 中仍然有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51743214/