KERAS中转移学习的两个模型的连接/组合



在KERAS中,我们如何连接/组合转移学习中的两个模型?

我有两种型号:model 1=我的模型型号2=经过训练的型号

我可以通过将模型2作为输入,然后将其输出传递给模型1来组合这些模型,这是传统的方式。

然而,我正在以另一种方式来做这件事。我想把模型1作为输入,然后把它的输出传递给模型2(即经过训练的模型1(。

这是完全相同的过程,只需确保您的模型的输出与其他模型的输入具有相同的形状。

from keras.models import Model
output = model2(model1.outputs)
joinedModel = Model(model1.inputs,output)

确保(如果你想要的话(在编译之前让模型2中的所有层都有trainable=False,这样训练就不会改变已经训练好的模型。


测试代码:

from keras.layers import *
from keras.models import Sequential, Model
#creating model 1 and model 2 -- the "previously existing models"
m1 = Sequential()
m2 = Sequential()
m1.add(Dense(20,input_shape=(50,)))
m1.add(Dense(30))
m2.add(Dense(5,input_shape=(30,)))
m2.add(Dense(11))
#creating model 3, joining the models 
out2 = m2(m1.outputs)
m3 = Model(m1.inputs,out2)
#checking out the results
m3.summary()
#layers in model 3
print("nthe main model:")
for i in m3.layers:
print(i.name)
#layers inside the last layer of model 3
print("ninside the submodel:")
for i in m3.layers[-1].layers:
print(i.name)

输出:

Layer (type)                 Output Shape              Param #   
=================================================================
dense_21_input (InputLayer)  (None, 50)                0         
_________________________________________________________________
dense_21 (Dense)             (None, 20)                1020      
_________________________________________________________________
dense_22 (Dense)             (None, 30)                630       
_________________________________________________________________
sequential_12 (Sequential)   (None, 11)                221       
=================================================================
Total params: 1,871
Trainable params: 1,871
Non-trainable params: 0
_________________________________________________________________
the main model:
dense_21_input
dense_21
dense_22
sequential_12
inside the submodel:
dense_23
dense_24

问题已经解决。

我使用了model.add()函数,然后添加了Model 1和Model 2所需的所有层。

下面的代码将在模型1之后添加模型2的第一个10层

for i in model2.layers[:10]: model.add(i)

最新更新