keras - Keras 功能 API:是否可以在分支模型上以分支方式阻止训练?
问题描述
我正在使用涉及多个分支的 Keras 训练一个有点复杂的模型。由于问题的结构,单独训练这些部分没有意义,但我不想将网络主分支的损失函数应用到与主分支合并的另一个分支(那个分支有自己的损失函数和输出)。我想知道是否有任何方法可以在功能 API 中实现这一点。
这是一个玩具模型定义,突出了我遇到的基本问题。层本身并不重要,重要的是模型的结构:
#Utility for subtracting some tensors
def diff(two_tensors):
x, y = two_tensors
return x - y
#Two inputs
in_1 = Input((128,))
in_2 = Input((128,))
#Main branch: Does something to the first input
branch_1 = Dense(128, activation='relu')(in_1)
branch_1 = Dense(128, activation='relu')(branch_1)
#Auxilliary classifier definition:
classifier = Sequential()
classifier.add(Dense(128, activation='relu'))
classifier.add(Dense(1, activation='linear'))
#This model asserts a confidence, and we'll use a sigmoid to actually classify
#The classifier takes the second input and the result of the main branch
pred_a = classifier(branch_1)
pred_b = classifier(in_2)
class_out = Activation('sigmoid')
class_a = class_out(pred_a)
class_b = class_out(pred_b)
#We calculate the difference between these two confidences in a lambda
pred_diff = Lambda(diff)([pred_a, pred_b])
#The main model uses this difference for another classification
branch_join = concatenate([pred_diff, branch_1], axis=-1)
main_output = Dense(20, activation='softmax')(branch_join)
#The model outputs the aux classifier's choices and the main prediction
model = Model(inputs=[in_1, in_2], outputs=[main_output, class_a, class_b])
losses = { 'main_output': 'sparse_categorical_crossentropy'
, 'class_a': 'binary_crossentropy'
, 'class_b': 'binary_crossentropy'
}
我只想在这个模型的中间训练分类器的两个输入的分类精度。但是,由于它连接到主分支,我认为主输出的损失也会通过这些层传播。在许多类似的情况下(比如简单的 GAN),答案是单独训练分类器,并在训练端到端系统时冻结分类器。但是,这不适用于我的用例,我想知道是否可以阻止 main_output 反向传播到分类器模型中的损失,同时仍然在其自己的输出上对其进行训练。
解决方案
推荐阅读
- c# - C# GridViewRowInfo 引发异常,但当我将复选框列值转换为布尔值时 DataGridViewRow 工作。
- java - 为什么for循环打印出意外的结果?
- makefile - Makefile 匹配规则的通配符先决条件
- reactjs - GatsbyJS:替换部分服务器端呈现的html
- ibm-mq - 克隆灾难恢复后集群队列管理器连接问题?
- docker - 将谷歌云 vm 实例的静态 IP 映射到 docker 容器 IP。
- javascript - Promise.then 未被调用
- python - 如何运行具有特定标签 docker-py 的容器
- javascript - 如何将 PDF 转换为 html 并将动态值转换为 html 文件
- git - Jenkins 不会同步 git clone 使用的 OpenShift Origin 机密