如果我正确地解决了问题,您可以在另一个模型中重用层甚至模型。
具有密集层的示例。假设您有 10 个输入
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
# defining 10 inputs in a List with (X,) shape
inputs = [Input(shape = (X,),name='input_{}'.format(k)) for k in
range(10)]
# defining a common Dense layer
D = Dense(64, name='one_layer_to_rule_them_all')
nets = [D(inp) for inp in inputs]
model = Model(inputs = inputs, outputs = nets)
model.compile(optimizer='adam', loss='categorical_crossentropy')
如果输入具有不同的形状,则此代码将不起作用。第一次调用 D 定义了它的属性。在此示例中,输出直接设置为网络。但当然,您可以连接、堆叠或任何您想要的。
现在,如果您有一些可训练的模型,您可以使用它来代替 D:
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
# defining 10 inputs in a List with (X,) shape
inputs = [Input(shape = (X,),name='input_{}'.format(k)) for k in
range(10)]
# defining a shared model with the same weights for all inputs
nets = [special_model(inp) for inp in inputs]
model = Model(inputs = inputs, outputs = nets)
model.compile(optimizer='adam', loss='categorical_crossentropy')
该模型的权重在所有输入之间共享。