【问题标题】:Custom Prediction from Complex Model (Functional API Keras)来自复杂模型的自定义预测(功能 API Keras)
【发布时间】:2020-06-10 09:55:44
【问题描述】:

以上是我使用 TF2 构建的 Keras 模型。我希望仅来自 Right Network 的预测通过 Concatenation 层馈送到 Batch 归一化层,尽管训练是在如上所示的两个输入层的网络上完成的。在预测期间,我只向 input_5 层提供输入,以从最终分类层获得输出。在预测过程中,我不希望左网络有任何贡献。

可能的解决方案: 1. 将 Target_Model、Batch-Norm 的权重保存为 Dense Layer 权重(使其成为 Sequential),并将 Source_Model 替换为形状为零的数组 (?, 512)。 创建了一个新模型并将所有这些部分添加到一起,以根据预测需要制定新模型,其中 Source_Model 被替换为 zeros 数组,以便将其提供给连接层。 问题:创建形状为 (?, 512) 的 zeros 数组时出错,因为未定义批量大小。

如何在 TF2.x 中解决这个问题?

有人知道其他技术吗?

【问题讨论】:

    标签: python tensorflow machine-learning keras deep-learning


    【解决方案1】:

    这可以是一个解决方案...

    ## define left model
    left = Input((33))
    xl = Dense(512)(left)
    left_model = Model(left, xl)
    
    ## define right model
    right = Input((10))
    xr = Dense(64)(right)
    right_model = Model(right, xr)
    
    ## define final shared model
    concat_inp = Input((576))
    x = BatchNormalization()(concat_inp)
    out = Dense(1)(x)
    combi_model = Model(concat_inp, out)
    
    ## combine left and right model
    concat = Concatenate()([left_model.output, right_model.output])
    ## combine branches with final shared model
    combi = combi_model(concat)
    
    full_model = Model([left_model.input, right_model.input], combi)
    
    # full_model.fit(...)
    

    在拟合整个模型后,我们可以提取我们需要的东西

    ## replace left branch in fitted model
    fake_left_input = Input((512))
    
    ## combine fake left branch with right fitted branch 
    new_concat = Concatenate()([fake_left_input, right_model.output])
    ## combine branches with final shared model
    new_combi = combi_model(new_concat)
    
    new_full_model = Model([fake_left_input, right_model.input], new_combi)
    new_full_model.summary()
    
    X_right_test = np.random.uniform(0,1, (20,10))
    X_left_test = np.zeros((len(X_right_test),512)) 
    new_full_model([X_left_test, X_right_test])
    

    【讨论】:

    • 感谢您的回答,但最后您传递的是假输入大小 (np.zeros(20,512)),您正在修复批量大小,但我们不知道批量大小如果从正确的网络产生的批量大小与我们的固定批量大小不匹配,那么运行时理想情况下会抛出连接错误。你也可以帮忙吗?
    • 20 是我选择的一个随机数,我没有看到这个问题......你可以传递你想要的每个数字。 new_full_model 用于进行推理,并且可以使用可变数量的样本对每个数组进行编码......唯一的限制是零样本的 n_sample 与右输入的 n_sample 匹配。换句话说,zeros 数组中的 20 等于右侧数组的 n_sample
    • 如果您更有信心,我在最后部分进行了编辑...不要忘记投票并接受它作为答案;-)
    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多