如何访问张量流::张量C++

How to access tensorflow::Tensor C++

本文关键字:张量流 张量 C++ 访问 何访问      更新时间:2023-10-16

我正在使用其C++ API运行Tensorflow。

我有以下调用,它在 finalOutput 中返回四个张量:

std::string str1 = "detection_boxes";
std::string str2 = "detection_scores";
std::string str3 = "detection_classes";
std::string str4 = "num_detections";
std::vector<Tensor> finalOutput;
status = session->Run({ {InputName, inputTensor} }, { str1, str2, str3, str4 }, {}, &finalOutput);
std::cout << finalOutput[0].DebugString() << std::endl;

print 语句输出以下内容:

"张量<类型:浮点形状:[1,100,4]>">

现在我有一个包含 100 个元素的张量,每个元素有 4 个值,我该如何遍历元素和值?

似乎我必须调用一个函数来返回 Eigen::TensorMap,然后以某种方式访问元素。 我只是不确定该怎么做。

非常感谢您的帮助!

我可以这样做

// tensor<float, 3>: 3 here because it's a 3-dimension tensor
auto output_detection_boxes = outputs[0].tensor<float, 3>();
std::cout << "detection boxes" << std::endl;
for (int i = 0; i < 100; ++i) {
for (int j = 0; j < 4; ++j)
// using (index_1, index_2, index_3) to access the element in a tensor
std::cout << output_detection_boxes(0, i, j)
<< "t";
std::cout << std::endl;
}

这是输出

detection boxes
0.0370  0.0465  0.8914  0.3171
0.0924  0.3944  0.9344  0.9769
0.0155  0.2988  0.8812  0.5263
0.1518  0.3817  0.9316  1.0000
0.0000  0.3285  0.8447  0.6669
0.0389  0.2030  0.8504  0.4749
...
(100 in total)