從零基礎入門Tensorflow2.0 ----九、44.3 keras模型轉換成savedmodel

胡侃有料發表於2020-06-17

every blog every motto:

0. 前言

以fashion_mnist 為例,keras模型轉換成savedmodel

1. 程式碼部分

1. 匯入模組

import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras

print(tf.__version__)
print(sys.version_info)
for module in mpl,np,pd,sklearn,tf,keras:
    print(module.__name__,module.__version__)

2. 讀取資料

fashion_mnist = keras.datasets.fashion_mnist
# print(fashion_mnist)
(x_train_all,y_train_all),(x_test,y_test) = fashion_mnist.load_data()
x_valid,x_train = x_train_all[:5000],x_train_all[5000:]
y_valid,y_train = y_train_all[:5000],y_train_all[5000:]
# 列印格式
print(x_valid.shape,y_valid.shape)
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)

3. 資料歸一化

# 資料歸一化
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
# x_train:[None,28,28] -> [None,784]
x_train_scaled = scaler.fit_transform(x_train.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
x_valid_scaled = scaler.transform(x_valid.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
x_test_scaled = scaler.transform(x_test.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)

4. 構建模型

# tf.keras.models.Sequential()
# 構建模型

# 建立物件
"""model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[28,28]))
model.add(keras.layers.Dense(300,activation='sigmoid'))
model.add(keras.layers.Dense(100,activation='sigmoid'))
model.add(keras.layers.Dense(10,activation='softmax'))"""

# 另一種寫法
model = keras.models.Sequential([
    keras.layers.Flatten(input_shape=[28,28]),
    keras.layers.Dense(300,activation='sigmoid'),
    keras.layers.Dense(100,activation='sigmoid'),
    keras.layers.Dense(10,activation='softmax')
])

# 
model.compile(loss='sparse_categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])

5. 訓練

# 開始訓練
history = model.fit(x_train_scaled,y_train,epochs=10,validation_data=(x_valid_scaled,y_valid))

6. 學習曲線

# 畫圖
def plot_learning_curves(history):
    pd.DataFrame(history.history).plot(figsize=(8,5))
    plt.grid(True)
    plt.gca().set_ylim(0,1)
    plt.show()
plot_learning_curves(history)

7. 測試集

model.evaluate(x_test_scaled,y_test,verbose=0)

8. keras模型轉換成savemodel

8.1 儲存成savemodel

# 儲存成savemodel
tf.saved_model.save(model,'keras_saved_graph')

8.2 展示save_model

注: jupyter notebook 中 以"!"開頭的為命令

# 命令列工具 !
!saved_model_cli show --dir keras_saved_graph --all

8.4 展示指定的簽名函式

!saved_model_cli show --dir keras_saved_graph --tag_set serve --signature_def serving_default

8.5 命令列測試

!saved_model_cli run --dir keras_saved_graph --tag_set serve --signature_def serving_default --input_exprs 'flatten_input=np.ones((1,28,28))'

8.6 用程式測試

# 用程式測試
load_saved_model = tf.saved_model.load('keras_saved_graph')
print(list(load_saved_model.signatures.keys()))

8.7 利用簽名函式

# 利用函式簽名
inference = load_saved_model.signatures['serving_default']
print(inference)
print(inference.structured_outputs)
results = inference(tf.constant(x_test_scaled[0:1]))
print(results)
print(results['dense_2'])

相關文章