【问题标题】:Google AI platform custom prediction routines with multiple inputs, how to read json inputs谷歌AI平台自定义多输入预测例程,如何读取json输入
【发布时间】:2020-04-06 02:05:53
【问题描述】:

为了使用 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()

我们对 google 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 框架所做的就是在实例上调用 .predict 方法(除非确实对数据进行了一些底层重塑。我找不到来源来了解到底发生了什么)

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

【问题讨论】:

    标签: google-cloud-platform google-cloud-ml


    【解决方案1】:

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

    为新模型的三个输入中的每一个创建一个单独的输入层(输入的名称是 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(...)
    

    【讨论】:

    • 输入在不同时间进入模型。例如,输入 1 被放入嵌入和 lstm 层,然后将其输出连接到输入 2。因此,我不能按照您的建议在一开始就进行连接和整形。相反,我需要有多个输入。但是如何编写我的 google AI 平台自定义预测例程来摄取包含数据的实例?
    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2018-07-25
    • 2011-11-04
    相关资源
    最近更新 更多