[英]Indexing tensorflow output tensor in c++
我正在使用C ++ API加载图形(* .pb)。 该图已经在Python中设置和训练,并具有图形的输入形状定义: tf.placeholder(tf.float32, [None, 84, 84, 1], name='in'
。这应该允许任意的脚批量大小。在开始会话并加载图形后,我采用矩形灰度OpenCV Mat图像,然后将其拆分为较小的方形图像,将其大小调整为所需的输入大小并将它们存储在矢量中:
cv::Size smallSize(splitLength, img_in.size().height);
std::vector<Mat> input_Images;
int y = 0;
for (int x = 0; x < img_in.cols; x += smallSize.width)
{
cv::Rect rect = cv::Rect(x,y, smallSize.width, smallSize.height);
cv::Mat temp = cv::Mat(img_in, rect);
cv::Size s(height_out, width_out);
cv::resize(temp,process_img,s,0,0,cv::INTER_CUBIC);
input_Images.push_back(process_img);
}
然后我把这个数组写成张量流量张量:
tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({input_Images.size(), height_out, width_out, 1}));
auto input_tensor_mapped = input_tensor.tensor<float, 4>();
for (int i = 0; i < input_Images.size(); i++) {
Mat image = input_Images[i];
const float * source_data = (float*) image.data;
for (int h = 0; h < image.rows; ++h) {
const float* source_row = source_data + (h * image.cols * image.channels());
for (int w = 0; w < image.cols; ++w) {
const float* source_pixel = source_row + (w * image.channels());
for (int c = 0; c < image.channels(); ++c) {
const float* source_value = source_pixel + c;
input_tensor_mapped(i, h, w, c) = *source_value;
}
}
}
}
我得到一个形状为[16,84,84,1]的张量。 然后我运行会话 :
session_create_status = session_deepcytometry->Run({{ inputLayer, nn_input_tensor}},{outputLayer},{},&finalOutput);
这似乎工作得很好。 当我运行std::cout finalOutput[0].DebugString() << "\\n";
我得到输出: stringTensor<type: float shape: [16,4] values: [7.8605752 10.652889 -24.507538]...>
在批量大小为1的情况下,它显示了我: stringTensor<type: float shape: [1,4] values: [7.8605752 10.652889 -24.507538]...>
finalOutput.size();
在任何一种情况下都是1。
如果批量大小为1,我使用简单循环检索类得分:
for(int i=0; i<nClasses; i++){
result.push_back(finalOutput[0].flat<float>()(i));
}
现在的问题是如果批量大小是16,我该怎么做?
你应该像开头一样访问张量。 如果输出形状的等级为2,则使用
auto finalOutputTensor = finalOutput[0].tensor<float, 2>();
和
for(int b=0; b<BatchSize;b++)
for(int i=0; i<nClasses; i++){
cout << b << "th output for class "<<i<<" is "<< finalOutputTensor(b, i) <<end;
}
在处理扁平张量(作为等效替代品)的情况下,您也可以使用
for(int b=0; b<BatchSize;b++)
for(int i=0; i<nClasses; i++){
cout << b << "th output for class "<<i<<" is "<< finalOutput[0].flat<float>()(b * nClasses + i) << end;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.