谷歌AI平台自定义多输入预测例程,如何读取json输入



对于使用Keras(Tensorflow 2.1(模型创建自定义预测例程,我很难弄清楚json输入的形式,以及如何在预测器类中为多个输入读取它们。文档中的所有自定义预测例程示例都使用简单的单一输入列表。例如,如果我们将输入发送为:

{"instances": [
{
"event_type_input": [1, 2, 20],
"event_dwelltime_input": [1.368, 0.017, 0.0],
"rf_input": [1.2, -2.8]},
{
"event_type_input": [14, 40, 20],
"event_dwelltime_input": [1.758, 13.392, 0.0],
"rf_input": [1.29, -2.87]}
]}

我们应该如何在预测器类中接收传入的json?

class MyPredictor(object):
def __init__(self, model):
self.model = model
def predict(self, instances, **kwargs):
inputs = np.array(instances) 
# The above example from the docs is wrong for multiple inputs
# What should our inputs be to get the inputs in the right shape 
# for our keras model?
outputs = self.model.predict(inputs)
return outputs.tolist()

我们对谷歌ai平台的json输入是一个字典列表。然而,对于keras模型,我们的输入需要是不同的形状,如下所示:

inputs = {
"event_type_input": np.array([[1, 2, 20], [14, 40, 20]]),
"event_dwelltime_input": np.array([[1.368, 0.017, 0.0], [1.758, 13.392, 0.0]])
"rf_input": np.array([[1.2, -2.8], [1.29, -2.87]]}
model.predict(inputs)

那么我所要做的只是重塑实例,这是对的吗?唯一令人困惑的是,如果使用tensorflow框架(而不是自定义预测例程(,它可以很好地处理json输入的预测,我认为tensorflow框架所做的只是在实例上调用.prdict方法(除非确实有一些数据的幕后重塑。我找不到来源来了解到底发生了什么(

主要问题:我们应该如何编写预测器类来接收实例,以便在其上运行model.prpredict方法?

我建议创建一个新的Keras模型并导出它。

为新模型的三个输入中的每一个创建一个单独的Input层(Input的名称是JSON结构中的名称(。然后,在此模型中,重塑输入,并从已训练的模型中借用权重/结构,然后导出新模型。类似这样的东西:

trained_model = keras.models.load_model(...) # trained model
input1 = keras.Input(..., name='event_type_input')
input2 = keras.Input(..., name='event_dwelltime_input')
input3 = keras.Input(..., name='rf_input')
export_inputs = keras.concatenate([input1, input2, input3])
reshaped_inputs = keras.layers.Lambda(...) # reshape to what the first hidden layer of your trained model expects
layer1 = trained_model.get_layer(index=1)(reshaped_inputs)
layer2 = trained_model.get_layer(index=2)(layer1) # etc. ...
...
exportModel = keras.Model(export_inputs, export_output) 
exportModel.save(...)

最新更新