简体   繁体   English

使用预先训练的模型训练模型

[英]Training a model using a pre-trained model

I have a pre-trained model in Keras. 我在Keras有一个预先训练过的模型。 I would like to train another model where the output of the model is input for the already trained model and the output of the already trained model is being used in the loss function of the untrained model. 我想训练另一个模型,其中模型的输出被输入用于已经训练的模型,并且已经训练的模型的输出被用在未训练模型的损失函数中。 Something like 就像是

in_a + mod_b(some kind of feedback from B here) --> Model A --> out_a --> Model B --> out_b

error  = (in_a - out_b)**2

and then use this error to train Model A. in_a can be treated as a constant in this system and there is a feedback loop as well 然后使用此错误来训练模型A. in_a可以在此系统中视为常量,并且还有一个反馈循环

Any ideas how to do this in keras or tensorflow 任何想法如何在keras或tensorflow中执行此操作

Here's an idea. 这是一个想法。 Build Model A until the output layer, which we'll assume is compatible with Model B's input layer. 构建模型A直到输出层,我们假设它与模型B的输入层兼容。 Also, let's assume you're Using a pretrained VGG16 as Model B. You'll load the model with pretrained weights: 另外,假设您使用预训练的VGG16作为模型B.您将使用预训练的权重加载模型:

from keras.applications.vgg16 import VGG16

# Model A is trainable
x = Input(shape=(32,))
x_d = Dense(10)(x)
model_a_out = Dense(10)(x_d)

# Model B
model_b = VGG16(weights='imagenet', include_top=True)
# Freeze Model B
for layer in model_b.layers:
    layer.trainable = False

# Set input to Model B as output from A
model_b.input = model_a_out

# Train as usual
model_b.compile... and model_b.fit ...

Another way of doing it is first you want to build A. and then: 另一种方法是首先要构建A.然后:

for layer in model_b.layers:
  new_layer = layer
  new_layer.trainable = False
  model_a.add(new_layer)

Check out the Keras Applications page for some ideas. 查看Keras Applications页面了解一些想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM