【发布时间】:2021-01-18 15:50:24
【问题描述】:
我经常使用 scikit-learn 管道来简化模型处理,我想知道在 Tensorflow 2.0 中使用 Keras 做类似事情的最简单方法。
我想做的是将 Keras 模型部署为 API 端点,然后将一段文本以 numpy 数组形式提交给它,并对其进行标记、填充和预测。但我不知道这样做的最短路径。
这里有一些示例代码:
from tensorflow import keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, Dense, Flatten
import numpy as np
sample_words = [
'The sky is blue',
'The sky delivers us many gifts',
'Wise men appreciate gifts for what they are, not what they are not',
'Wherever you go, there you are',
'Don\'t pass judgment onto others, or you will quickly be judged yourself'
]
y = np.array([1, 0, 1, 1, 0])
tokenizer = Tokenizer(num_words=10)
tokenizer.fit_on_texts(sample_words)
train_sequences = tokenizer.texts_to_sequences(sample_words)
train_sequences = pad_sequences(train_sequences, maxlen=7)
mod = Sequential([
Embedding(10, 2, input_length=7),
Flatten(),
Dense(3, activation='relu'),
Dense(1, activation='sigmoid')
])
mod.compile(optimizer='adam', loss='binary_crossentropy')
mod.fit(train_sequences, y)
这个想法是,如果我有一个网络表单并且有人提交了一个带有“今天的天空很漂亮”的表单,我可以将它包装在一个 numpy 数组中,将它发送到端点(将在 Google 上设置) Cloud),并对其进行填充、标记和预测。
在 scikit 中学习它就像:pipe = make_pipeline(tokenizer, mod),然后从那里开始。
我感觉有一些解决方案包括td.Datasets,但我希望 keras 有一些对用户更友好的东西。
【问题讨论】:
-
我不太明白你的问题。您已经拥有所有必要的代码。 1。你需要标记你的文本,2。您需要将其 3 填充到模型预测中并返回结果。为什么不把这个函数放到自定义函数中呢?
-
@MichaelJanz 我必须在 Google Cloud 上为 API 端点部署一个保存的模型,如果保存的模型将这些处理步骤自动链接在一起会更容易(我认为)。
-
我也有同样的问题。你找到解决办法了吗?
标签: tensorflow keras google-cloud-platform tensorflow2.0