在 TensorFlow 中一个接一个地预测多个输出

原文标题Predicting Multiple Outputs one after another in Tensorflow

我想创建一个可以预测两个输出的模型。我做了一些研究,发现可以通过使用 Tensorflow Keras 中的功能 API 创建两个分支(用于预测两个输出)来做到这一点,但我有另一种方法,看起来像这样:architecture

i.e。given a input, first I want to predict output1 and then based on that I want to predict output2.

那么如何在 Tensorflow 中做到这一点?请让我知道如何进行培训,即。我将如何为每个 output1 和 output2 传递标签,然后计算损失。谢谢

原文链接:https://stackoverflow.com//questions/71588670/predicting-multiple-outputs-one-after-another-in-tensorflow

回复

我来回复
  • Mohammad Khoshbin的头像
    Mohammad Khoshbin 评论

    您可以使用 tensorflow 的功能 API 来完成。我用某种伪代码编写它:

    Inputs = your_input
    x = hidden_layers()(Inputs)
    Output1 = Dense()(x)
    x = hidden_layers()(Output1)
    Output2 = Dense()(x)
    

    因此,如果您需要,您可以将其分为两个模型:

    model1 = tf.keras.models.Model(inputs=[Input], outputs=[Output1])
    model2 = tf.keras.models.Model(inputs=[Input], outputs=[Output2])
    

    或者在一个模型中拥有一切:

    model = tf.keras.models.Model(inputs=[Input], outputs=[Output2])
    Output1_pred = model.get_layer('Output1').output
    

    更新:
    为了训练具有两个输出的模型,您可以将模型分成两个部分并分别训练每个部分,如下所示:

    model1 = tf.keras.models.Model(inputs=[Input], outputs=[Output1])
    model2 = tf.keras.models.Model(inputs=[model1.get_layer('Output1').output], outputs=[Output2])
    model1.cmpile(...)
    model1.fit(...)
    
    for layer in model1.layers:
        layer.trainable = False
    
    model2.compile(...)
    model2.fit(...)
    
    2年前 0条评论
  • Oscar的头像
    Oscar 评论

    您实际上可以通过@Mohammad 修改出色的答案,以组成一个具有两个输出的独特模型。

    Inputs = your_input
    x = hidden_layers()(Inputs)
    Output1 = Dense()(x)
    x = hidden_layers()(Output1)
    Output2 = Dense()(x)
    
    model = tf.keras.models.Model(inputs=[Inputs], outputs=[Output1, Output2])
    model.compile(loss=[loss_1, loss_2], loss_weights=[0.5, 0.5], optimizer=sgd, metrics=['accuracy'])
    

    当然,您可以根据自己的情况更改权重、优化器和指标。

    然后模型必须在(X, y1, y2)where(y1, y2)分别是 output1 和 output2 标签的数据上进行训练。

    2年前 0条评论