作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在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/
我是一名优秀的程序员,十分优秀!