[英]How to recursively expand/resolve/flatten nested models in keras?
Let's say I built a nested model like this: 假设我建立了这样的嵌套模型:
from keras.models import Sequential, Model
from keras.layers.core import Input, Dense
model_1 = Sequential()
model_1.add(Dense(...))
model_1.add(Dense(...))
input_2 = Input(...)
output_2 = Dense(...)(input_2)
model_2 = Model(inputs=input_2, outputs=output_2)
model = Sequential()
model.add(model_1)
model.add(model_2)
How can I transform this recursively into a "flat" model, that does not contain any Model
or Sequential
layers. 如何将其递归转换为不包含任何
Model
层或Sequential
层的“平面”模型。
Since model_1
and model_2
might have been trained in advance the parameters should be conserved during the transformation. 由于
model_1
和model_2
可能已经预先训练,因此在转换过程中应保留参数。
I had a similar problem, and I got a working solution, but this doesn't seem very elegant. 我有一个类似的问题,并且我有一个可行的解决方案,但这似乎不是很优雅。
The basic idea is to iterate through the layers of the sub-models and add them to the overall model one by one rather than adding the entire sub-models. 基本思想是遍历子模型的各个层,并将它们逐个添加到整个模型中,而不是添加整个子模型。
model = Sequential()
for layer1 in model1.layers:
model.add(layer1)
for layer2 in model2.layers:
model.add(layer2)
If the model already includes nested models, it is possible to iterate over them via: 如果模型已经包含嵌套模型,则可以通过以下方法对其进行迭代:
model_flat = Sequential()
for layer_nested in model.get_layer('nested_model').layers:
model_flat.add(layer_nested)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.