【发布时间】:2017-05-31 00:56:29
【问题描述】:
我想在我导出的 Keras 模型中包含我的自定义预处理逻辑,以便在 Tensorflow Serving 中使用。
我的预处理执行字符串标记化并使用外部字典将每个标记转换为索引以输入到嵌入层:
from keras.preprocessing import sequence
token_to_idx_dict = ... #read from file
# Custom Pythonic pre-processing steps on input_data
tokens = [tokenize(s) for s in input_data]
token_idxs = [[token_to_idx_dict[t] for t in ts] for ts in tokens]
tokens_padded = sequence.pad_sequences(token_idxs, maxlen=maxlen)
模型架构和训练:
model = Sequential()
model.add(Embedding(max_features, 128, input_length=maxlen))
model.add(LSTM(128, activation='sigmoid'))
model.add(Dense(n_classes, activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam')
model.fit(x_train, y_train)
由于模型将在 Tensorflow Serving 中使用,我想将所有预处理逻辑合并到模型本身(在导出的模型文件中编码)。
问:如何仅使用 Keras 库来做到这一点?
我发现this guide 解释了如何结合 Keras 和 Tensorflow。但我仍然不确定如何将所有内容导出为一个模型。
我知道 Tensorflow 有内置的字符串拆分、file I/O 和 dictionary lookup operations。
使用 Tensorflow 操作的预处理逻辑:
# Get input text
input_string_tensor = tf.placeholder(tf.string, shape={1})
# Split input text by whitespace
splitted_string = tf.string_split(input_string_tensor, " ")
# Read index lookup dictionary
token_to_idx_dict = tf.contrib.lookup.HashTable(tf.contrib.lookup.TextFileInitializer("vocab.txt", tf.string, 0, tf.int64, 1, delimiter=","), -1)
# Convert tokens to indexes
token_idxs = token_to_idx_dict.lookup(splitted_string)
# Pad zeros to fixed length
token_idxs_padded = tf.pad(token_idxs, ...)
问:如何将这些 Tensorflow 预定义的预处理操作和我的 Keras 层一起用于训练模型,然后将模型导出为“黑盒”以用于 Tensorflow Serving?
【问题讨论】:
-
找到解决方案了吗?
-
@OphirYoktan 请参阅下面的答案。
标签: python tensorflow keras tensorflow-serving