[英]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.