【问题标题】:Train selective branch of multi output keras model训练多输出keras模型的选择性分支
【发布时间】:2017-05-31 09:12:00
【问题描述】:

我有一个多输出 Keras 模型,其结构类似于:

s = some_shared_layers()(input)
non_trainable1 = Dense(trainable=False) (s) 
non_trainable2 = Dense(trainable=False) (s) 
trainable = Dense() (s) 

model = Model(input, outputs=[non_trainable1, non_trainable2, trainable])

我的模型首先计算前向传递并使用前 2 个输出来操纵输入。然后它计算另一个前向传递以获得第三个输出。

out1, out2,_ =model.predict(input_data) 
processed_data = foo(input_data, out1, out2) 
_,_, out3 = model.predict(processed_data)

我应该如何调用model.fit() 来仅训练trainable 层?如果我排除其他输出的损失,Keras 会发出警告 we will not be expecting any data to be passed to "non_trainable1" during training 并将它们从计算图中排除。

有没有更好的方法来构建这个任务的模型?

【问题讨论】:

    标签: keras


    【解决方案1】:

    如果我理解正确,您根本不需要这些层,实际上您应该有两个模型,一个仅用于预测,另一个用于训练。

    不可训练:

    model1 = Model(input, [non_trainable1, non_trainable2])
    #model 1 doesn't need to be compiled, since you won't train it    
    

    可训练:

    model2 = Model(input, trainable)
    model2.compile(loss=onlyTheLossForTrainable)     
    

    使用它们:

    out1, out2 =model1.predict(input_data) 
    processed_data = foo(input_data, out1, out2) 
    
    model2.fit(processed_data, expected_outputs, ....)    
    

    【讨论】:

    • 我目前正在使用它作为一种解决方法,如果我按照您的描述运行代码,它就会起作用。但是如果我尝试以更复杂的方式使用处理函数foo——比如在ImageDataGenerator内部——那么model2.fit_generator()会引发ValueError: Tensor "non_trainable1" is not an element of this graph.
    • 为什么在发电机里面??你到底想在发电机内部做什么?听起来您使用的是张量而不是预测。
    • 我正在处理图像并使用生成器进行数据增强。作为一个天真的第一次尝试,我尝试将foo 作为preprocessing_function 参数传递(参考docs)。 foo 获取图像,调用model1.predict() 并返回编辑后的图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2021-01-15
    • 2019-11-21
    • 2021-08-13
    相关资源
    最近更新 更多