gpt4 book ai didi

c++ - torch C++ : Getting the value of a int tensor by using *. 数据()

转载 作者:行者123 更新时间:2023-12-04 18:00:52 26 4
gpt4 key购买 nike

在Libtorch的C++版本中,我发现可以通过*tensor_name[0].data<float>()得到一个浮点张量的值。 ,其中代替 0我可以使用任何其他有效索引。但是,当我定义了一个 int张量通过添加选项 at::kInt进入张量创建,我不能使用这个结构来获取张量的值,即类似 *tensor_name[0].data<at::kInt>() 的东西或 *tensor_name[0].data<int>()不起作用,调试器一直说 Couldn't find method at::Tensor::data<at::kInt>Couldn't find method at::Tensor::data<int> .
我可以通过 auto value_array = tensor_name=accessor<int,1>() 获取值,但更容易使用 *tensor_name[0].data<int>() .你能告诉我如何使用 data<>()获取 int 的值张量?
我也有同样的问题 bool类型。

最佳答案

使用 item<dtype>()从张量中得到一个标量。

int main() {
torch::Tensor tensor = torch::randint(20, {2, 3});
std::cout << tensor << std::endl;
int a = tensor[0][0].item<int>();
std::cout << a << std::endl;
return 0;
}

~/l/build ❯❯❯ ./example-app
3 10 3
2 5 8
[ Variable[CPUFloatType]{2,3} ]
3

以下代码打印 0 (在 Linux 上使用稳定的 libtorch 进行测试):
#include <torch/script.h>
#include <iostream>

int main(int argc, const char* argv[])
{
auto indx = torch::zeros({20},at::dtype(at::kLong));
std::cout << indx[0].item<long>() << std::endl;

return 0;
}

关于c++ - torch C++ : Getting the value of a int tensor by using *. 数据<int>(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54200785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com