如何将一个模型分为两个单独的模型? [英] How to split a model into two seperate models?

查看:182
本文介绍了如何将一个模型分为两个单独的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For example I have a model with 3 intermediate layers:

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

并希望将其拆分为

Model2 : Input2 --> L1 --> L2

Model3 : Input3 --> L3.

使用功能性API可以很容易地将这两个堆栈堆叠在一起.但是我不确定如何做相反的事情.

It is easy to stack these two to get the first one using functional API. But I'm not sure how to do the opposite thing.

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

The first split model can be obtained by: Model(Input1, L2.output), but the second one is not that easy. What is the simplest way to do this?

示例代码:

# 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)

我想构建上述的model2model3,它们在model1已经存在时(可能从磁盘加载)与model1共享权重.

I want to build model2 and model3 described above that share weights with model1 while model1 already exists (maybe loaded from disk).

谢谢!

推荐答案

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

In short, extra Input is needed. Because the input tensor is different from the intermediate tensor.

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

First define the shared layers: 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

Remember that 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)).

To define model2, you have to first define a new input tensor input2=Input(shape=(64,)). Then model2 = Model(input2, l3(l2(input2)).

这篇关于如何将一个模型分为两个单独的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆