【发布时间】:2019-04-25 20:57:25
【问题描述】:
我正在使用 Tensorflow 2.0,并且能够训练 CNN 来对 3 通道图像进行图像分类。我在数据输入管道(如下所示)中执行图像预处理,并希望在服务模型本身中包含预处理功能。我的模型使用 TF Serving Docker 容器和 Predict API。
用于训练的数据输入管道基于https://www.tensorflow.org/alpha/tutorials/load_data/images 的文档。
我的管道图像预处理函数是load_and_preprocess_from_path_label:
def load_and_preprocess_path(image_path):
# Load image
image = tf.io.read_file(image_path)
image = tf.image.decode_png(image)
# Normalize to [0,1] range
image /= 255
# Convert to HSV and Resize
image = tf.image.rgb_to_hsv(image)
image = tf.image.resize(image, [HEIGHT, WIDTH])
return image
def load_and_preprocess_from_path_label(image_path, label):
return load_and_preprocess_path(image_path), label
通过图像路径列表,管道使用 load_and_preprocess_from_path_label 中的 tf 函数预取并执行图像预处理:
all_image_paths, all_image_labels = parse_labeled_image_paths()
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(all_image_paths, all_image_labels, test_size=0.2)
# Create a TensorFlow Dataset of training images and labels
ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))
image_label_ds = ds.map(load_and_preprocess_from_path_label)
BATCH_SIZE = 32
IMAGE_COUNT = len(all_image_paths)
ds = image_label_ds.apply(tf.data.experimental.shuffle_and_repeat(buffer_size=IMAGE_COUNT))
ds = ds.batch(BATCH_SIZE)
ds = ds.prefetch(buffer_size=AUTOTUNE)
# Create image pipeline for model
image_batch, label_batch = next(iter(ds))
feature_map_batch = model(image_batch)
# Train model
model.fit(ds, epochs=5)
我发现以前的 Tensorflow 示例使用 serving_input_fn(),并使用了在 Tensorflow 2.0 中似乎不再存在的 tf.placeholder。
Tensorflow 2.0 中 serving_input_fn 的示例显示在 https://www.tensorflow.org/alpha/guide/saved_model 上。由于我使用的是 Predict API,看起来我需要类似于:
serving_input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(...)
# Save the model with the serving preprocessing function
model.export_saved_model(MODEL_PATH, serving_input_fn)
理想情况下,服务模型将接受任何大小的 3 通道图像样本的 4D 张量,并在分类之前对它们执行初始图像预处理(解码图像、归一化、转换为 HSV 和调整大小)。
如何在 Tensorflow 2.0 中创建具有类似于我的 load_and_preprocess_path 函数的预处理函数的 serving_input_fn?
【问题讨论】:
标签: tensorflow2.0