成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專(zhuān)欄INFORMATION COLUMN

Tensorflow Lite介紹

jhhfft / 3353人閱讀

摘要:簡(jiǎn)介是針對(duì)移動(dòng)設(shè)備和嵌入式設(shè)備的輕量化解決方案,占用空間小,低延遲。支持浮點(diǎn)運(yùn)算和量化模型,并已針對(duì)移動(dòng)平臺(tái)進(jìn)行優(yōu)化,可以用來(lái)創(chuàng)建和運(yùn)行自定義模型。此外,轉(zhuǎn)換的方式有兩種,的方式和命令行方式。生成為了將模型轉(zhuǎn)為,模型需要導(dǎo)出。

簡(jiǎn)介

Tensorflow Lite是針對(duì)移動(dòng)設(shè)備和嵌入式設(shè)備的輕量化解決方案,占用空間小,低延遲。Tensorflow Lite在android8.1以上的設(shè)備上可以通過(guò)ANNA啟用硬件加速。

支持浮點(diǎn)運(yùn)算和量化模型,并已針對(duì)移動(dòng)平臺(tái)進(jìn)行優(yōu)化,可以用來(lái)創(chuàng)建和運(yùn)行自定義模型。開(kāi)發(fā)者也可以在模型中添加自定義操作。

FlatBuffer格式

具有在移動(dòng)設(shè)備運(yùn)行更快的內(nèi)核解釋器

支持通過(guò)Tensorflow訓(xùn)練好的模型轉(zhuǎn)換為T(mén)ensorflow Lite格式(pd,h5等都可以)

當(dāng)支持所有優(yōu)化操作時(shí),模型小于300k,當(dāng)僅支持inception v3和mobilenet模型優(yōu)化時(shí),模型小于200k

預(yù)訓(xùn)練模型:

inception v3:用于目標(biāo)檢測(cè)

MobileNets:專(zhuān)門(mén)針對(duì)移動(dòng)端的模型,具有低延遲,高速度,低內(nèi)存,可用于圖像識(shí)別,目標(biāo)檢測(cè),圖像分割,但是精度小于inception v3

量化版本的MobileNets,通過(guò)將float-32轉(zhuǎn)為int-8,在CPU上擁有更快的速度

支持java,c++API

以上談到的預(yù)訓(xùn)練模型基于ImageNet數(shù)據(jù)集訓(xùn)練,支持1000種類(lèi)別。如果此數(shù)據(jù)集不能滿足你的項(xiàng)目需要,你需要準(zhǔn)備自己的數(shù)據(jù)集和標(biāo)簽,使用遷移學(xué)習(xí)重新訓(xùn)練模型。

模型結(jié)構(gòu)

Tensorflow Lite模型的數(shù)據(jù)格式與Tensorflow桌面端不同,需要使用Tensorflow Lite轉(zhuǎn)換為.tflite格式,然后應(yīng)用到移動(dòng)端。
模型結(jié)構(gòu):

java-API:包裝C++API,以便在android上使用java調(diào)用

C++-API:加載Tensorflow Lite模型和解釋器

解釋器:執(zhí)行模型一系列核心操作,支持選擇內(nèi)核加載。全部加載300kb,不加載只有100kb

在android8.1以上設(shè)備,可通過(guò)相關(guān)api進(jìn)行硬件加速(硬件支持的情況下),否則在CPU執(zhí)行

轉(zhuǎn)換模型格式

Tensorflow Lite轉(zhuǎn)換器支持以下格式:

使用python API執(zhí)行SavedModel保存的模型文件

tf.keras保存的.h5模型文件

轉(zhuǎn)換后的GraphDef文件

轉(zhuǎn)換GraphDef文件

Tensorflow模型一般保存為.pd或.pdtxt格式的文件,要轉(zhuǎn)換為T(mén)ensorflow Lite支持的文件,首先需要進(jìn)行frozen操作。此操作處理多個(gè)不同格式的文件:

tf.GraphDef(pd,pdtxt):圖文件,包含操作,張量,變量的定義

checkpoint(.ckpt):包含變量,不包含解釋器

tensorflow lite(.tflite):序列化的FlatBuffer文件,包含所有需要的文件

checkpoint文件包含訓(xùn)練權(quán)重,tf.graphdef文件包含圖結(jié)構(gòu)。凍結(jié)操作就是將上述文件進(jìn)行合并操作
使用命令行,執(zhí)行該操作的示例如下:
freeze_graph --input_graph=/demo/mobilenet_v1_224.pd
--input_checkpoint=/demo/checkpoints/mobilenet-1001.ckpt
--input_binary=True
--output_graph=/demo/frozen_mobilenet_v1_224.pd
--output_node_names=/demo/MobileNetV1/Predictions/Reshape_1

input_binary:讀取的文件是否是二進(jìn)制文件,如:pd和pdtxt文件

android端使用Tensorflow Lite

可以使用android studio和源碼編譯兩種方式,此處我們介紹第一種(由于你懂的原因,開(kāi)vpn會(huì)比較順利些)。

安裝android studio

SDK大于26,NDK大于14

導(dǎo)入工程項(xiàng)目,路徑:tensorflow/lite/examples

默認(rèn)使用mobilenet模型,如要使用inception模型,先下載模型文件并拷貝至asset文件夾,然后修改Camera2BasicFragment文件:
classifier = new ImageClassifierQuantizedMobileNet(getActivity())改為:
classifier = new ImageClassifierFloatInception(getActivity())

Tensorflow Lite轉(zhuǎn)換器

上圖是Tensorflow Lite轉(zhuǎn)換器的工作流程,清晰明了,就不做過(guò)多介紹了。此外,轉(zhuǎn)換的方式有兩種,python api的方式和命令行方式。

從Session中導(dǎo)出GraphDef

使用tf.Session將Tensorflow模型轉(zhuǎn)為T(mén)ensorflow Lite模型

import tensorflow as tf

img = tf.placeholder(name="img", dtype=tf.float32, shape=(1, 64, 64, 3))
var = tf.get_variable("weights", dtype=tf.float32, shape=(1, 64, 64, 3))
val = img + var
out = tf.identity(val, name="out")

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  converter = tf.lite.TFLiteConverter.from_session(sess, [img], [out])
  tflite_model = converter.convert()
  open("converted_model.tflite", "wb").write(tflite_model)
從file中導(dǎo)出GraphDef

以下代碼展示怎樣將.pd或.pdtxt文件轉(zhuǎn)為T(mén)ensorflow Lite模型支持的FlateBuffer格式文件。

import tensorflow as tf

graph_def_file = "/path/to/Downloads/mobilenet_v1_1.0_224/frozen_graph.pb"
input_arrays = ["input"]
output_arrays = ["MobilenetV1/Predictions/Softmax"]

converter = tf.lite.TFLiteConverter.from_frozen_graph(
  graph_def_file, input_arrays, output_arrays)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
將SaveModle導(dǎo)出
import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
tf.keras文件導(dǎo)出
import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_keras_model_file("keras_model.h5")
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
量化模型
import tensorflow as tf

img = tf.placeholder(name="img", dtype=tf.float32, shape=(1, 64, 64, 3))
const = tf.constant([1., 2., 3.]) + tf.constant([1., 4., 4.])
val = img + const
out = tf.fake_quant_with_min_max_args(val, min=0., max=1., name="output")

with tf.Session() as sess:
  converter = tf.lite.TFLiteConverter.from_session(sess, [img], [out])
  converter.inference_type = tf.lite.constants.QUANTIZED_UINT8
  input_arrays = converter.get_input_arrays()
  converter.quantized_input_stats = {input_arrays[0] : (0., 1.)}  # mean, std_dev
  tflite_model = converter.convert()
  open("converted_model.tflite", "wb").write(tflite_model)
TensorFlow Lite Python解釋器

代碼展示如何使用Tensorflow Lite解釋器讀取.tflite文件。

import numpy as np
import tensorflow as tf

# 加載模型并分配張量
interpreter = tf.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()

# 獲取輸入輸出張量
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 隨機(jī)生成測(cè)試數(shù)據(jù),測(cè)試模型輸出
input_shape = input_details[0]["shape"]
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]["index"], input_data)

interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]["index"])
print(output_data)
Tensorflow2.0轉(zhuǎn)換器使用

如圖所示,Tensorflow2.0與之前相比,少了凍結(jié)graph模塊,增加了Concrete Fn。

生成concrete Fn

為了將Tensorflow2.0模型轉(zhuǎn)為T(mén)ensorflow Lite,模型需要導(dǎo)出concrete Fn。這是因?yàn)門(mén)ensorflow2.0中,eager execution是默認(rèn)設(shè)置,雖然調(diào)試更加便利,但是它沒(méi)有保存圖,因?yàn)椴荒苤苯討?yīng)用到移動(dòng)設(shè)備。不過(guò),可以使用tf.function包裝,這樣保存的模型就包含圖,可以轉(zhuǎn)換為T(mén)ensorflow Lite所需要的FlatBuffer格式文件。

class BasicModel(tf.Module):

  def __init__(self):
    self.const = None

  @tf.function
  def pow(self, x):
    if self.const is None:
      self.const = tf.Variable(2.)
    return x ** self.const

concrete Fn聲明的圖可以被轉(zhuǎn)換為T(mén)ensorflow Lite模型或者使用SaveModel導(dǎo)出。為了導(dǎo)出此方法,需要聲明signature,使用方法如下:

在tf.function中聲明input_signature

將tf.TensorSpec傳值給get_concrete_funtion

將input傳值給get_concrete_funtion

import tensorflow as tf

root = tf.Module()

# 初始化一次變量值
root.var = None

@tf.function
def exported_function(x):
  
  if root.var is None:
    root.var = tf.Variable(tf.random.uniform([2, 2]))
  root.const = tf.constant([[37.0, -23.0], [1.0, 4.0]])
  root.mult = tf.matmul(root.const, root.var)
  return root.mult * x

root.func = exported_function

concrete_func = root.func.get_concrete_function(
  tf.TensorSpec([1, 1], tf.float32))
Python api執(zhí)行the TensorFlow Lite converter

Tensorflow2.0中轉(zhuǎn)換Tensorflow Lite模型使用tf.lite.TFLiteConverter.from_concrete_function(),示例如下:

import tensorflow as tf

# 創(chuàng)建模型
root = tf.train.Checkpoint()
root.v1 = tf.Variable(3.)
root.v2 = tf.Variable(2.)
root.f = tf.function(lambda x: root.v1 * root.v2 * x)

# 保存模型
export_dir = "/tmp/test_saved_model"
input_data = tf.constant(1., shape=[1, 1])
to_save = root.f.get_concrete_function(input_data)
tf.saved_model.save(root, export_dir, to_save)

# 加載模型并獲取concrete fn.
model = tf.saved_model.load(export_dir)
concrete_func = model.signatures[
  tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]

# 設(shè)置input shape
concrete_func.inputs[0].set_shape(input_data.shape)

# 轉(zhuǎn)換模型
converter = tf.lite.TFLiteConverter.from_concrete_function(concrete_func)
tflite_model = converter.convert()
TensorFlow Lite 推斷

TensorFlow Lite推斷一般執(zhí)行以下步驟:

加載.tflite模型

處理數(shù)據(jù)以適應(yīng)模型input

調(diào)用API,創(chuàng)建解析器,運(yùn)行模型

獲取模型輸出結(jié)果

如何選擇模型

如圖所示,大模型高精度,高延遲;小模型低精度,低延遲,模型的選擇需要根據(jù)你的項(xiàng)目需求進(jìn)行選擇。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/19975.html

相關(guān)文章

  • tensorflow嵌入式

    好的,下面是一篇關(guān)于TensorFlow嵌入式編程技術(shù)的文章。 TensorFlow是一種流行的機(jī)器學(xué)習(xí)框架,它可以用于訓(xùn)練和部署深度神經(jīng)網(wǎng)絡(luò)。然而,TensorFlow通常被視為一個(gè)大型的、需要高性能計(jì)算機(jī)的框架,這使得它在嵌入式系統(tǒng)上的應(yīng)用變得困難。但是,最近的TensorFlow版本已經(jīng)開(kāi)始支持嵌入式設(shè)備,這使得它可以在諸如智能手機(jī)、智能家居設(shè)備和嵌入式系統(tǒng)等小型設(shè)備上運(yùn)行。 在本文中,...

    h9911 評(píng)論0 收藏1903
  • tensorflow量化訓(xùn)練

    好的,下面是一篇關(guān)于TensorFlow量化訓(xùn)練的編程技術(shù)類(lèi)文章。 TensorFlow量化訓(xùn)練是一種優(yōu)化模型大小和性能的技術(shù),它通過(guò)減少模型中參數(shù)的精度來(lái)實(shí)現(xiàn)這一目標(biāo)。在這篇文章中,我們將介紹如何使用TensorFlow實(shí)現(xiàn)量化訓(xùn)練,并探討它如何提高模型的性能和效率。 首先,讓我們來(lái)了解一下TensorFlow量化訓(xùn)練的基本概念。量化訓(xùn)練是一種將模型參數(shù)從浮點(diǎn)數(shù)轉(zhuǎn)換為定點(diǎn)數(shù)的技術(shù)。在這種情況...

    ivan_qhz 評(píng)論0 收藏234
  • 玩轉(zhuǎn)TensorFlow Lite:有道云筆記實(shí)操案例分享

    摘要:如何進(jìn)行操作本文將介紹在有道云筆記中用于文檔識(shí)別的實(shí)踐過(guò)程,以及都有些哪些特性,供大家參考。年月發(fā)布后,有道技術(shù)團(tuán)隊(duì)第一時(shí)間跟進(jìn)框架,并很快將其用在了有道云筆記產(chǎn)品中。微軟雅黑宋體以下是在有道云筆記中用于文檔識(shí)別的實(shí)踐過(guò)程。 這一兩年來(lái),在移動(dòng)端實(shí)現(xiàn)實(shí)時(shí)的人工智能已經(jīng)形成了一波潮流。去年,谷歌推出面向移動(dòng)端和嵌入式的神經(jīng)網(wǎng)絡(luò)計(jì)算框架TensorFlowLite,將這股潮流繼續(xù)往前推。Tens...

    Hanks10100 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<