【问题标题】:where is torch.tensor.item() defined at the Github?在 Github 上的 torch.tensor.item() 定义在哪里?
【发布时间】:2021-04-03 08:04:35
【问题描述】:

我是火炬新手。

当我学习下面这样的手电筒教程时,
我很好奇 tensor.item() 是在哪里定义的

import torch
a = torch.tensor([1])
print( a.item() )  # it works without problem.

为了找到我不知道的东西,

首先,我使用了 VScode。但我明白了。
enter image description here
不喜欢这样
enter image description here

第二,我在the torch Github搜索了“def item()”
但是,我找不到。 T^T

你能告诉我tensor.item()在哪里定义the Github吗?

或者

Class_torch.tensor's Menber functions(Method function) 是在哪里定义的??

【问题讨论】:

    标签: python pytorch torch


    【解决方案1】:

    简答:

    torch/csrc/autograd/python_variable_indexing.cpp:268

    长答案:

    我希望你喜欢 C++。 ;)

    首先要知道item() 不是(通常)大多数 Python 类中的方法。相反,为了方便起见,Python 将对 item() 的调用转换为其他底层方法,例如 __getitem__()。知道:

    class Tensor 定义在torch/tensor.py:40

    Torch 的大部分底层计算密集型功能都是用 C 和 C++ 实现的,包括 Tensor。 “class Tensor”基于Torch._C.TensorBase,它通过torch/csrc/autograd/python_variable.cpp:812的C API提供给Python

    THPVariableType 是提供给 Python 的映射,用于描述 Python 对象上可用的 C++ 函数。它在torch/csrc/autograd/python_variable 中定义。与您相关的部分是 tp_as_mapping 条目(第 752 行),它为实现映射协议的对象提供函数 - 基本上是 Pyton 类对象 (Python Documentation)

    第 725 行的 THPVariable_as_mapping 结构提供了映射方法。第二个变量提供了用于按索引获取项目的下标函数 (Python documentation)

    因此,C++函数TPHVariable_getitem提供了Torch.Tensor.item()的实现,定义在torch/csrc/autograd/python_variable_indexing

    【讨论】:

    • 谢谢。我完全理解。我喜欢 C++! ;)
    • 您能否提供指向您描述的item 行为的文档链接?这听起来与iter 的行为和相关功能相似,但我还没有找到item 的官方文档。
    • Instead, Python converts calls to item() into other underlying methods like __getitem__() as a convenience. 这表明存在一些自动化,但我认为方法 item 只是称为 item 并没有什么特别之处。
    猜你喜欢
    • 1970-01-01
    • 2013-04-09
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 2016-02-19
    • 2016-12-31
    相关资源
    最近更新 更多