如何将模型拆分为两个单独的模型?

时间:2017-04-11 14:56:14

标签: keras

例如,我有一个包含3个中间层的模型:

Model1 : Input1 --> L1 --> L2 --> L3

并希望将其拆分为

Model2 : Input2 --> L1 --> L2

Model3 : Input3 --> L3

使用功能API很容易将这两个堆叠起来以获得第一个。但我不确定如何做相反的事情。

第一个拆分模型可以通过:Model(Input1, L2.output)获得,但第二个不是那么容易。最简单的方法是什么?

示例代码:

# the first model
input1 = Input(shape=(784,))
l1 = Dense(64, activation='relu')(inputs)
l2 = Dense(64, activation='relu')(l1)
l3 = Dense(10, activation='softmax')(l2)
model1 = Model(inputs, l3)

我想构建上面描述的model2model3model1共享权重,而model1已经存在(可能是从磁盘加载)。

谢谢!

1 个答案:

答案 0 :(得分:3)

简而言之,需要额外的Input。因为输入张量中间张量不同。

首先定义共享层: l1 = Dense(64, activation='relu') l2 = Dense(64, activation='relu') l3 = Dense(10, activation='softmax')

请记住 input1 = Input(shape=(784,)) # input1 is a input tensor o1 = l1(input1) # o1 is an intermediate tensor

Model1可以定义为model1 = Model(input1, l3(l2(l1(input1))) )

要定义model2,您必须先定义新的输入张量input2=Input(shape=(64,))。然后是model2 = Model(input2, l3(l2(input2))