27.TensorFlow Serving REST API - 鐵人賽示範
下載資料及訓練模型
- 由於重點在如何起一個TF Severing 服務,資料採用
keras.datasets.cifar10進行示範,CIFAR10為小型的影像分類資料集,具有50,000筆訓練資料集與10,000筆測試資料集,皆為32X32像素圖片。更多資訊參閱官方介紹。
| Label | Description |
|---|---|
| 0 | airplane |
| 1 | automobile |
| 2 | bird |
| 3 | cat |
| 4 | deer |
| 5 | dog |
| 6 | frog |
| 7 | horse |
| 8 | ship |
| 9 | truck |
# TensorFlow and tf.keras
# !pip install -Uq grpcio==1.26.0
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
import os
import subprocess
- 建立模型
fashion_mnist = keras.datasets.cifar10
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# scale the values to 0.0 to 1.0
train_images = train_images / 255.0
test_images = test_images / 255.0
# reshape for feeding into the model
train_images = train_images.reshape(train_images.shape[0], 32, 32, 3)
test_images = test_images.reshape(test_images.shape[0], 32, 32, 3)
class_names = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']
print(f'train_images.shape: {train_images.shape}, of {train_images.dtype}')
print(f'test_images.shape: {test_images.shape}, of {test_images.dtype}')
- 訓練與評估模型
model = keras.Sequential([
keras.layers.Conv2D(
input_shape=(32,32,3),
filters=8,
kernel_size=3,
strides=2,
activation='relu',
name='Conv1'),
keras.layers.Flatten(),
keras.layers.Dense(10, name='Dense')
])
model.summary()
testing = False
epochs = 5
model.compile(
optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[keras.metrics.SparseCategoricalAccuracy()]
)
model.fit(train_images, train_labels, epochs=epochs)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')
儲存模型
- 將模型保存為SavedModel格式,以便將模型加載到 TensorFlow Serving 中。
- TensorFlow Serving允許我們在發出推理請求時選擇要使用的模型版本或“可服務”版本。每個版本將導出到給定路徑下的不同子目錄。為此,需在目錄創建 protobuf 文件,並將包含一個版本號。
- 以下會在
/tmp/建立版次版次version = 1之相關檔案。
import tempfile
MODEL_DIR = tempfile.gettempdir()
version = 1
export_path = os.path.join(MODEL_DIR, str(version))
print(f'export_path = {export_path}')
tf.keras.models.save_model(
model,
export_path,
overwrite=True,
include_optimizer=True,
save_format=None,
signatures=None,
options=None
)
print('\nSaved model:')
!ls -l {export_path}