[英]In Torch C++ API, How to write to the internal data of a tensor fastly?
[英]Torch C++: Getting the value of a int tensor by using *.data<int>()
在 Libtorch 的 C++ 版本中,我發現我可以通過*tensor_name[0].data<float>()
獲取浮點張量的值,其中我可以使用任何其他有效索引代替0
。 但是,當我通過在張量創建中添加選項at::kInt
來定義一個int
張量時,我無法使用此結構來獲取張量的值,即*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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.