我想在我导出的Keras模型中包含我的自定义预处理逻辑,以用于Tensorflow服务.
我的预处理执行字符串标记化并使用外部字典将每个标记转换为索引以输入到嵌入层:
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)
Run Code Online (Sandbox Code Playgroud)
模型架构和培训:
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)
Run Code Online (Sandbox Code Playgroud)
由于该模型将用于Tensorflow服务,我想将所有预处理逻辑合并到模型本身(在导出的模型文件中编码).
问:我怎样才能使用Keras库?
我发现本指南解释了如何结合Keras和Tensorflow.但我仍然不确定如何将所有东西都作为一个模型出口.
我知道Tensorflow有内置的字符串拆分,文件I/O和字典查找操作.
使用Tensorflow操作的预处理逻辑:
# Get input text
input_string_tensor = tf.placeholder(tf.string, shape={1})
# Split input text by …Run Code Online (Sandbox Code Playgroud) 假设我有一个简单的神经网络,其输入层和在tensorflow中编程的单个卷积层:
# Input Layer
input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])
# Convolutional Layer #1
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=32,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
Run Code Online (Sandbox Code Playgroud)
我遗漏了网络定义的任何其他部分features.
如果我想在此卷积层之后添加LSTM层,我将必须使卷积层TimeDistributed(以keras的语言),然后将TimeDistributed层的输出放入LSTM.
Tensorflow提供对tf.keras.layers中 keras层的访问.我可以直接在tensorflow代码中使用keras层吗?如果是这样,怎么样?我是否也可以使用tf.keras.layers.lstm来实现LSTM层?
所以一般来说:纯粹的张量流代码和keras代码的混合是否可能,我可以使用tf.keras.layers吗?