TensorFlow訓(xùn)練好的模型以tensorflow原生方式保存成protobuf文件后可以用許多方式部署運(yùn)行膛檀。
例如:通過(guò) tensorflow-js 可以用javascrip腳本加載模型并在瀏覽器中運(yùn)行模型脐恩。
通過(guò) tensorflow-lite 可以在移動(dòng)和嵌入式設(shè)備上加載并運(yùn)行TensorFlow模型舍肠。
通過(guò) tensorflow-serving 可以加載模型后提供網(wǎng)絡(luò)接口API服務(wù),通過(guò)任意編程語(yǔ)言發(fā)送網(wǎng)絡(luò)請(qǐng)求都可以獲取模型預(yù)測(cè)結(jié)果呵燕。
通過(guò) tensorFlow for Java接口棠绘,可以在Java或者spark(scala)中調(diào)用tensorflow模型進(jìn)行預(yù)測(cè)。
我們主要介紹tensorflow serving部署模型再扭、使用spark(scala)調(diào)用tensorflow模型的方法氧苍。
〇,tensorflow serving模型部署概述
使用 tensorflow serving 部署模型要完成以下步驟泛范。
(1) 準(zhǔn)備protobuf模型文件让虐。
(2) 安裝tensorflow serving。
(3) 啟動(dòng)tensorflow serving 服務(wù)罢荡。
(4) 向API服務(wù)發(fā)送請(qǐng)求赡突,獲取預(yù)測(cè)結(jié)果。
可通過(guò)以下colab鏈接測(cè)試效果《tf_serving》:
https://colab.research.google.com/drive/1vS5LAYJTEn-H0GDb1irzIuyRB8E3eWc8
%tensorflow_version 2.x
import tensorflow as tf
print(tf.__version__)
from tensorflow.keras import *
一柠傍,準(zhǔn)備protobuf模型文件
我們使用tf.keras 訓(xùn)練一個(gè)簡(jiǎn)單的線性回歸模型麸俘,并保存成protobuf文件辩稽。
import tensorflow as tf
from tensorflow.keras import models,layers,optimizers
## 樣本數(shù)量
n = 800
## 生成測(cè)試用數(shù)據(jù)集
X = tf.random.uniform([n,2],minval=-10,maxval=10)
w0 = tf.constant([[2.0],[-1.0]])
b0 = tf.constant(3.0)
Y = X@w0 + b0 + tf.random.normal([n,1],
mean = 0.0,stddev= 2.0) # @表示矩陣乘法,增加正態(tài)擾動(dòng)
## 建立模型
tf.keras.backend.clear_session()
inputs = layers.Input(shape = (2,),name ="inputs") #設(shè)置輸入名字為inputs
outputs = layers.Dense(1, name = "outputs")(inputs) #設(shè)置輸出名字為outputs
linear = models.Model(inputs = inputs,outputs = outputs)
linear.summary()
## 使用fit方法進(jìn)行訓(xùn)練
linear.compile(optimizer="rmsprop",loss="mse",metrics=["mae"])
linear.fit(X,Y,batch_size = 8,epochs = 100)
tf.print("w = ",linear.layers[1].kernel)
tf.print("b = ",linear.layers[1].bias)
## 將模型保存成pb格式文件
export_path = "./data/linear_model/"
version = "1" #后續(xù)可以通過(guò)版本號(hào)進(jìn)行模型版本迭代與管理
linear.save(export_path+version, save_format="tf")
#查看保存的模型文件
!ls {export_path+version}
assets saved_model.pb variables
# 查看模型文件相關(guān)信息
!saved_model_cli show --dir {export_path+str(version)} --all
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:
signature_def['__saved_model_init_op']:
The given SavedModel SignatureDef contains the following input(s):
The given SavedModel SignatureDef contains the following output(s):
outputs['__saved_model_init_op'] tensor_info:
dtype: DT_INVALID
shape: unknown_rank
name: NoOp
Method name is:
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['inputs'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 2)
name: serving_default_inputs:0
The given SavedModel SignatureDef contains the following output(s):
outputs['outputs'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 1)
name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict
WARNING:tensorflow:From /tensorflow-2.1.0/python3.6/tensorflow_core/python/ops/resource_variable_ops.py:1786: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
Defined Functions:
Function Name: '__call__'
Option #1
Callable with:
Argument #1
inputs: TensorSpec(shape=(None, 2), dtype=tf.float32, name='inputs')
Argument #2
DType: bool
Value: False
Argument #3
DType: NoneType
Value: None
Option #2
Callable with:
Argument #1
inputs: TensorSpec(shape=(None, 2), dtype=tf.float32, name='inputs')
Argument #2
DType: bool
Value: True
Argument #3
DType: NoneType
Value: None
Function Name: '_default_save_signature'
Option #1
Callable with:
Argument #1
inputs: TensorSpec(shape=(None, 2), dtype=tf.float32, name='inputs')
Function Name: 'call_and_return_all_conditional_losses'
Option #1
Callable with:
Argument #1
inputs: TensorSpec(shape=(None, 2), dtype=tf.float32, name='inputs')
Argument #2
DType: bool
Value: True
Argument #3
DType: NoneType
Value: None
Option #2
Callable with:
Argument #1
inputs: TensorSpec(shape=(None, 2), dtype=tf.float32, name='inputs')
Argument #2
DType: bool
Value: False
Argument #3
DType: NoneType
Value: None
二惧笛,安裝 tensorflow serving
安裝 tensorflow serving 有2種主要方法:通過(guò)Docker鏡像安裝,通過(guò)apt安裝逞泄。
通過(guò)Docker鏡像安裝是最簡(jiǎn)單患整,最直接的方法拜效,推薦采用。
Docker可以理解成一種容器各谚,其上面可以給各種不同的程序提供獨(dú)立的運(yùn)行環(huán)境紧憾。
一般業(yè)務(wù)中用到tensorflow的企業(yè)都會(huì)有運(yùn)維同學(xué)通過(guò)Docker 搭建 tensorflow serving.
無(wú)需算法工程師同學(xué)動(dòng)手安裝,以下安裝過(guò)程僅供參考昌渤。
不同操作系統(tǒng)機(jī)器上安裝Docker的方法可以參照以下鏈接赴穗。
Windows: https://www.runoob.com/docker/windows-docker-install.html
MacOs: https://www.runoob.com/docker/macos-docker-install.html
CentOS: https://www.runoob.com/docker/centos-docker-install.html
安裝Docker成功后,使用如下命令加載 tensorflow/serving 鏡像到Docker中
docker pull tensorflow/serving
三膀息,啟動(dòng) tensorflow serving 服務(wù)
!docker run -t --rm -p 8501:8501 \
-v "/Users/.../data/linear_model/" \
-e MODEL_NAME=linear_model \
tensorflow/serving & >server.log 2>&1
四般眉,向API服務(wù)發(fā)送請(qǐng)求
可以使用任何編程語(yǔ)言的http功能發(fā)送請(qǐng)求,下面示范linux的 curl 命令發(fā)送請(qǐng)求潜支,以及Python的requests庫(kù)發(fā)送請(qǐng)求甸赃。
!curl -d '{"instances": [1.0, 2.0, 5.0]}' \
-X POST http://localhost:8501/v1/models/linear_model:predict
{
"predictions": [[3.06546211], [5.01313448]
]
}
import json,requests
data = json.dumps({"signature_name": "serving_default", "instances": [[1.0, 2.0], [5.0,7.0]]})
headers = {"content-type": "application/json"}
json_response = requests.post('http://localhost:8501/v1/models/linear_model:predict',
data=data, headers=headers)
predictions = json.loads(json_response.text)["predictions"]
print(predictions)
[[3.06546211], [6.02843142]]