C++ TensorflowLite模型验证的过程详解
程序员文章站
2022-03-30 13:01:57
故事是这样的:有一个手撑检测的tflite模型,需要在开发板上跑起来。手机版本的已成熟,要移植到开发板上。现在要验证tflite模型文件在板子上的运行结果要和手机上一致。前提:为了多次重复测试,在an...
故事是这样的:
有一个手撑检测的tflite模型,需要在开发板上跑起来。手机版本的已成熟,要移植到开发板上。现在要验证tflite模型文件在板子上的运行结果要和手机上一致。
前提:为了多次重复测试,在android端使用了同一帧数据(从一个录制的mp4中固定取一张图)测试代码如下图
下面是测试过程
记录下android版api运行推理前的图片数据文件(经过了规一化处理,所以都是-1~1之间的float数据)
这一步卡在了写float数据到二进制文件中,c++读出来有问题换了个方案,直接存储float字符串
private void savefile(float[] pfimagedata) { try { file file = new file(environment.getexternalstoragepublicdirectory(environment.directory_downloads).getabsolutepath() + "/tfimg"); stringbuilder sb = new stringbuilder(); for (float val : pfimagedata) { //保留4位小数,这里可以改为其他值 sb.append(string.format("%.4f", val)); sb.append("\r\n"); } filewriter out = new filewriter(file); //文件写入流 out.write(sb.tostring()); out.close(); } catch (exception e) { e.printstacktrace(); log.e("melon", "存储文件异常," + e.getmessage()); } }
拿着这个文件在板子上输入到tflite模型中
测试代码,主要是runinference()和read_file()
/* copyright 2017 the tensorflow authors. all rights reserved. licensed under the apache license, version 2.0 (the "license"); you may not use this file except in compliance with the license. you may obtain a copy of the license at http://www.apache.org/licenses/license-2.0 unless required by applicable law or agreed to in writing, software distributed under the license is distributed on an "as is" basis, without warranties or conditions of any kind, either express or implied. see the license for the specific language governing permissions and limitations under the license. ==============================================================================*/ #include "tensorflow/lite/examples/label_image/label_image.h" #include <fcntl.h> // nolint(build/include_order) #include <getopt.h> // nolint(build/include_order) #include <sys/time.h> // nolint(build/include_order) #include <sys/types.h> // nolint(build/include_order) #include <sys/uio.h> // nolint(build/include_order) #include <unistd.h> // nolint(build/include_order) #include <cstdarg> #include <cstdio> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <unordered_set> #include <vector> #include "absl/memory/memory.h" #include "tensorflow/lite/examples/label_image/bitmap_helpers.h" #include "tensorflow/lite/examples/label_image/get_top_n.h" #include "tensorflow/lite/examples/label_image/log.h" #include "tensorflow/lite/kernels/register.h" #include "tensorflow/lite/optional_debug_tools.h" #include "tensorflow/lite/profiling/profiler.h" #include "tensorflow/lite/string_util.h" #include "tensorflow/lite/tools/command_line_flags.h" #include "tensorflow/lite/tools/delegates/delegate_provider.h" namespace tflite { namespace label_image { double get_us(struct timeval t) { return (t.tv_sec * 1000000 + t.tv_usec); } using tflitedelegateptr = tflite::interpreter::tflitedelegateptr; using provideddelegatelist = tflite::tools::provideddelegatelist; class delegateproviders { public: delegateproviders() : delegate_list_util_(¶ms_) { delegate_list_util_.addalldelegateparams(); } // initialize delegate-related parameters from parsing command line arguments, // and remove the matching arguments from (*argc, argv). returns true if all // recognized arg values are parsed correctly. bool initfromcmdlineargs(int *argc, const char **argv) { std::vector<tflite::flag> flags; // delegate_list_util_.appendcmdlineflags(&flags); const bool parse_result = flags::parse(argc, argv, flags); if (!parse_result) { std::string usage = flags::usage(argv[0], flags); log(error) << usage; } return parse_result; } // according to passed-in settings `s`, this function sets corresponding // parameters that are defined by various delegate execution providers. see // lite/tools/delegates/readme.md for the full list of parameters defined. void mergesettingsintoparams(const settings &s) { // parse settings related to gpu delegate. // note that gpu delegate does support opencl. 'gl_backend' was introduced // when the gpu delegate only supports opengl. therefore, we consider // setting 'gl_backend' to true means using the gpu delegate. if (s.gl_backend) { if (!params_.hasparam("use_gpu")) { log(warn) << "gpu deleate execution provider isn't linked or gpu " "delegate isn't supported on the platform!"; } else { params_.set<bool>("use_gpu", true); // the parameter "gpu_inference_for_sustained_speed" isn't available for // ios devices. if (params_.hasparam("gpu_inference_for_sustained_speed")) { params_.set<bool>("gpu_inference_for_sustained_speed", true); } params_.set<bool>("gpu_precision_loss_allowed", s.allow_fp16); } } // parse settings related to nnapi delegate. if (s.accel) { if (!params_.hasparam("use_nnapi")) { log(warn) << "nnapi deleate execution provider isn't linked or nnapi " "delegate isn't supported on the platform!"; } else { params_.set<bool>("use_nnapi", true); params_.set<bool>("nnapi_allow_fp16", s.allow_fp16); } } // parse settings related to hexagon delegate. if (s.hexagon_delegate) { if (!params_.hasparam("use_hexagon")) { log(warn) << "hexagon deleate execution provider isn't linked or " "hexagon delegate isn't supported on the platform!"; } else { params_.set<bool>("use_hexagon", true); params_.set<bool>("hexagon_profiling", s.profiling); } } // parse settings related to xnnpack delegate. if (s.xnnpack_delegate) { if (!params_.hasparam("use_xnnpack")) { log(warn) << "xnnpack deleate execution provider isn't linked or " "xnnpack delegate isn't supported on the platform!"; } else { params_.set<bool>("use_xnnpack", true); params_.set<bool>("num_threads", s.number_of_threads); } } } // create a list of tflite delegates based on what have been initialized (i.e. // 'params_'). std::vector<provideddelegatelist::provideddelegate> createalldelegates() const { return delegate_list_util_.createallrankeddelegates(); } private: // contain delegate-related parameters that are initialized from command-line // flags. tflite::tools::toolparams params_; // a helper to create tflite delegates. provideddelegatelist delegate_list_util_; }; // takes a file name, and loads a list of labels from it, one per line, and // returns a vector of the strings. it pads with empty strings so the length // of the result is a multiple of 16, because our model expects that. // std::vector<uint8_t> read_file(const std::string &input_bmp_name) // { // int begin, end; // std::ifstream file(input_bmp_name, std::ios::in | std::ios::binary); // if (!file) // { // log(fatal) << "input file " << input_bmp_name << " not found"; // exit(-1); // } // begin = file.tellg(); // file.seekg(0, std::ios::end); // end = file.tellg(); // size_t len = end - begin; // log(info) << "len: " << len; // std::vector<uint8_t> img_bytes(len); // file.seekg(0, std::ios::beg); // file.read(reinterpret_cast<char *>(img_bytes.data()), len); // return img_bytes; // } /** * 读取文件 */ std::vector<float> read_file(const std::string &input_bmp_name) { int begin, end; std::ifstream file(input_bmp_name, std::ios::in | std::ios::binary); if (!file) { log(fatal) << "input file " << input_bmp_name << " not found"; exit(-1); } begin = file.tellg(); file.seekg(0, std::ios::end); end = file.tellg(); size_t len = end - begin; log(info) << "len: " << len; std::vector<float> img_bytes; file.seekg(0, std::ios::beg); string strline = ""; float temp; while (getline(file, strline)) { temp = atof(strline.c_str()); img_bytes.push_back(temp); } log(info) << "文件读取完成:" << input_bmp_name; return img_bytes; } /** * 运行推理 */ void runinference(settings *settings) { if (!settings->model_name.c_str()) { log(error) << "no model file name"; exit(-1); } std::unique_ptr<tflite::flatbuffermodel> model; std::unique_ptr<tflite::interpreter> interpreter; model = tflite::flatbuffermodel::buildfromfile(settings->model_name.c_str()); if (!model) { log(error) << "failed to mmap model " << settings->model_name; exit(-1); } settings->model = model.get(); log(info) << "loaded model " << settings->model_name; model->error_reporter(); log(info) << "resolved reporter"; tflite::ops::builtin::builtinopresolver resolver; tflite::interpreterbuilder(*model, resolver)(&interpreter); //生成interpreter if (!interpreter) { log(error) << "failed to construct interpreter"; exit(-1); } interpreter->setallowfp16precisionforfp32(settings->allow_fp16); if (settings->verbose) { log(info) << "tensors size: " << interpreter->tensors_size(); log(info) << "nodes size: " << interpreter->nodes_size(); log(info) << "inputs: " << interpreter->inputs().size(); log(info) << "input(0) name: " << interpreter->getinputname(0); int t_size = interpreter->tensors_size(); for (int i = 0; i < t_size; i++) { if (interpreter->tensor(i)->name) log(info) << i << ": " << interpreter->tensor(i)->name << ", " << interpreter->tensor(i)->bytes << ", " << interpreter->tensor(i)->type << ", " << interpreter->tensor(i)->params.scale << ", " << interpreter->tensor(i)->params.zero_point; } } if (settings->number_of_threads != -1) { interpreter->setnumthreads(settings->number_of_threads); } int image_width = 128; int image_height = 128; int image_channels = 3; // std::vector<uint8_t> in = read_bmp(settings->input_bmp_name, &image_width, &image_height, &image_channels, settings); std::vector<float> file_bytes = read_file(settings->input_bmp_name); for (int i = 0; i < 100; i++) { //和android的输入做对比 log(info) << i << ": " << file_bytes[i]; } /* inputs()[0]得到输入张量数组中的第一个张量,也就是classifier中唯一的那个输入张量; input是个整型值,是张量列表中的引索 */ int input = interpreter->inputs()[0]; log(info) << "input: " << input; const std::vector<int> inputs = interpreter->inputs(); const std::vector<int> outputs = interpreter->outputs(); log(info) << "number of inputs: " << inputs.size(); log(info) << "input index: " << inputs[0]; log(info) << "number of outputs: " << outputs.size(); log(info) << "outputs index1: " << outputs[0] << ",outputs index2: " << outputs[1]; if (interpreter->allocatetensors() != ktfliteok) { //加载所有tensor log(error) << "failed to allocate tensors!"; exit(-1); } if (settings->verbose) printinterpreterstate(interpreter.get()); // 从输入张量的原数据中得到输入尺寸 tfliteintarray *dims = interpreter->tensor(input)->dims; int wanted_height = dims->data[1]; int wanted_width = dims->data[2]; int wanted_channels = dims->data[3]; settings->input_type = interpreter->tensor(input)->type; //typed_tensor返回一个经过固定数据类型转换的tensor指针 //以input为索引,在tflitetensor* content_.tensors这个张量表得到具体的张量 //返回该张量的data.raw,它指示张量正关联着的内存块 // resize<float>(interpreter->typed_tensor<float>(input), in.data(), // image_height, image_width, image_channels, wanted_height, // wanted_width, wanted_channels, settings); //赋值给input tensor float *inputp = interpreter->typed_input_tensor<float>(0); log(info) << "file_bytes size: " << file_bytes.size(); for (int i = 0; i < file_bytes.size(); i++) { inputp[i] = file_bytes[i]; } struct timeval start_time, stop_time; gettimeofday(&start_time, nullptr); for (int i = 0; i < settings->loop_count; i++) { //调用模型进行推理 if (interpreter->invoke() != ktfliteok) { log(error) << "failed to invoke tflite!"; exit(-1); } } gettimeofday(&stop_time, nullptr); log(info) << "invoked"; log(info) << "average time: " << (get_us(stop_time) - get_us(start_time)) / (settings->loop_count * 1000) << " ms"; const float threshold = 0.001f; int output = interpreter->outputs()[1]; log(info) << "output: " << output; log(info) << "interpreter->tensors_size: " << interpreter->tensors_size(); tflitetensor *tensor = interpreter->tensor(output); tfliteintarray *output_dims = tensor->dims; // assume output dims to be something like (1, 1, ... ,size) auto output_size = output_dims->data[output_dims->size - 1]; log(info) << "索引为" << output << "的输出张量的-" << "output_size: " << output_size; for (int i = 0; i < output_dims->size; i++) { log(info) << "元数据有:" << output_dims->data[i]; } float *prediction = interpreter->typed_output_tensor<float>(1); float classificators[1][896][1]; memcpy(classificators, prediction, 896 * 1 * sizeof(float)); // float classificators[1][896][18]; // memcpy(classificators, prediction, 896 * 18 * sizeof(float)); //输出分类结果 for (float(&r)[896][1] : classificators) { for (float(&p)[1] : r) { for (float &q : p) { std::cout << q << ' '; } std::cout << std::endl; } std::cout << std::endl; } } int main(int argc, char **argv) { delegateproviders delegate_providers; bool parse_result = delegate_providers.initfromcmdlineargs( &argc, const_cast<const char **>(argv)); if (!parse_result) { return exit_failure; } settings s; int c; while (true) { static struct option long_options[] = { {"accelerated", required_argument, nullptr, 'a'}, {"allow_fp16", required_argument, nullptr, 'f'}, {"count", required_argument, nullptr, 'c'}, {"verbose", required_argument, nullptr, 'v'}, {"image", required_argument, nullptr, 'i'}, {"labels", required_argument, nullptr, 'l'}, {"tflite_model", required_argument, nullptr, 'm'}, {"profiling", required_argument, nullptr, 'p'}, {"threads", required_argument, nullptr, 't'}, {"input_mean", required_argument, nullptr, 'b'}, {"input_std", required_argument, nullptr, 's'}, {"num_results", required_argument, nullptr, 'r'}, {"max_profiling_buffer_entries", required_argument, nullptr, 'e'}, {"warmup_runs", required_argument, nullptr, 'w'}, {"gl_backend", required_argument, nullptr, 'g'}, {"hexagon_delegate", required_argument, nullptr, 'j'}, {"xnnpack_delegate", required_argument, nullptr, 'x'}, {nullptr, 0, nullptr, 0}}; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long(argc, argv, "a:b:c:d:e:f:g:i:j:l:m:p:r:s:t:v:w:x:", long_options, &option_index); /* detect the end of the options. */ if (c == -1) break; switch (c) { case 'a': s.accel = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'b': s.input_mean = strtod(optarg, nullptr); break; case 'c': s.loop_count = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'e': s.max_profiling_buffer_entries = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'f': s.allow_fp16 = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'g': s.gl_backend = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'i': s.input_bmp_name = optarg; break; case 'j': s.hexagon_delegate = optarg; break; case 'l': s.labels_file_name = optarg; break; case 'm': s.model_name = optarg; break; case 'p': s.profiling = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'r': s.number_of_results = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 's': s.input_std = strtod(optarg, nullptr); break; case 't': s.number_of_threads = strtol( // nolint(runtime/deprecated_fn) optarg, nullptr, 10); break; case 'v': s.verbose = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'w': s.number_of_warmup_runs = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'x': s.xnnpack_delegate = strtol(optarg, nullptr, 10); // nolint(runtime/deprecated_fn) break; case 'h': case '?': /* getopt_long already printed an error message. */ exit(-1); default: exit(-1); } } delegate_providers.mergesettingsintoparams(s); runinference(&s); return 0; } } // namespace label_image } // namespace tflite int main(int argc, char **argv) { return tflite::label_image::main(argc, argv); }
运行指令 ./ws_app --tflite_model libnewpalm_detection.tflite --image tfimg对比推理前的输入一致
android端
开发板上
对比推理后的输出一致 android端
开发板端
到此这篇关于c++ tensorflowlite模型验证的文章就介绍到这了,更多相关c++ tensorflowlite模型验证内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!