一、使用TensorFlowlite 構(gòu)建iOS自定義版本
- 由于TensorFlowlite 提供的 cocoapods 版本 支持到iOS9;所以需要使用手動編譯源碼瓮恭,構(gòu)建靜態(tài)包支持iOS8以上系統(tǒng);
- TensorFlow目前支持swift和OC厦坛,如果想使用直接cococapads集成狰闪;
二辛润、在iOS使用C++ api
- 使用api 之前 需要你準(zhǔn)備好lite版的model永淌;model訓(xùn)練完成之后轉(zhuǎn)換為lite即可
- 加載model的類:
class FlatBufferModel {
public:
// Builds a model based on a file.
// Caller retains ownership of `error_reporter` and must ensure its lifetime
// is longer than the FlatBufferModel instance.
// Returns a nullptr in case of failure.
static std::unique_ptr<FlatBufferModel> BuildFromFile(
const char* filename,
ErrorReporter* error_reporter = DefaultErrorReporter());
// Builds a model based on a pre-loaded flatbuffer.
// Caller retains ownership of the buffer and should keep it alive until
// the returned object is destroyed. Caller also retains ownership of
// `error_reporter` and must ensure its lifetime is longer than the
// FlatBufferModel instance.
// Returns a nullptr in case of failure.
// NOTE: this does NOT validate the buffer so it should NOT be called on
// invalid/untrusted input. Use VerifyAndBuildFromBuffer in that case
static std::unique_ptr<FlatBufferModel> BuildFromBuffer(
const char* caller_owned_buffer, size_t buffer_size,
ErrorReporter* error_reporter = DefaultErrorReporter());
}
- C++ 加載model 的步驟
構(gòu)建FlatBufferModel崎场,并且從構(gòu)建的FlatBufferModel中初始化Interpreter實(shí)例;
可以選擇性地進(jìn)行優(yōu)化Tensor;
設(shè)置Tensor的值遂蛀;
調(diào)用運(yùn)行推理谭跨;
讀取Tensor的輸出值
使用Interpreter對象注意事項(xiàng):
Tensor用整數(shù)值表示,避免使用字符串進(jìn)行比較李滴;
訪問Interpreter避免在多個線程中并發(fā)訪問饺蚊;
Tensor的輸入和輸出內(nèi)存分配使用AllocateTensors() 在重置大小之后進(jìn)行
tflite::FlatBufferModel model(path_to_model);
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::InterpreterBuilder(*model, resolver)(&interpreter);
// Resize input tensors, if desired.
interpreter->AllocateTensors();
float* input = interpreter->typed_input_tensor<float>(0);
// Fill `input`.
interpreter->Invoke();
float* output = interpreter->typed_output_tensor<float>(0);