上图是我使用TF2构建的Keras模型。我希望预测时仅从右侧网络获取输出,并通过连接层输入到批量归一化层,尽管训练时使用了如图所示的包含两个输入层的网络。在预测过程中,我只向input_5层输入数据,以获取最终分类层的输出。我不希望左侧网络在预测时有任何贡献。
可能的解决方案:1. 保存了目标模型的权重,将批量归一化层的权重转移到密集层(使其成为顺序模型),并用形状为(?, 512)的零数组替换源模型。创建了一个新模型,并将这些部分组合在一起,形成了用于预测的新模型,其中源模型被零数组替换,以便将其输入到连接层。问题:在创建形状为(?, 512)的零数组时出现错误,因为批量大小未定义。
如何在TF2.x中解决这个问题?
有没有人知道其他技术?
回答:
这可以是一个解决方案…
## 定义左侧模型left = Input((33))xl = Dense(512)(left)left_model = Model(left, xl)## 定义右侧模型right = Input((10))xr = Dense(64)(right)right_model = Model(right, xr)## 定义最终共享模型concat_inp = Input((576))x = BatchNormalization()(concat_inp)out = Dense(1)(x)combi_model = Model(concat_inp, out)## 结合左侧和右侧模型concat = Concatenate()([left_model.output, right_model.output])## 将分支与最终共享模型结合combi = combi_model(concat)full_model = Model([left_model.input, right_model.input], combi)# full_model.fit(...)
在拟合整个模型后,我们可以提取我们需要的部分
## 在拟合的模型中替换左侧分支fake_left_input = Input((512))## 结合假的左侧分支和拟合的右侧分支 new_concat = Concatenate()([fake_left_input, right_model.output])## 将分支与最终共享模型结合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])