有没有办法将节点添加到现有 Keras 模型中的层?如果是这样,最有效的方法是什么?另外,有没有可能做同样的事情但有层?即向现有 Keras 模型添加一个新层(例如,在输入层之后)。我知道的一种方法是通过迭代和克隆模型的每一层来使用 Keras 函数式 API,以便创建具有所需更改的原始模型的“副本”,但这是完成此任务的最有效方法吗?
1 回答

鸿蒙传说
TA贡献1865条经验 获得超7个赞
您可以获取模型中某个层的输出并从中构建另一个模型:
import tensorflow as tf
# One simple model
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation='relu')(inputs)
outputs = tf.keras.layers.Dense(5, activation='softmax')(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
# Make a second model starting from layer in previous model
x2 = tf.keras.layers.Dense(8, activation='relu')(model.layers[1].output)
outputs2 = tf.keras.layers.Dense(7, activation='softmax')(x2)
model2 = tf.keras.Model(inputs=model.input, outputs=outputs2)
请注意,在这种情况下model,model2共享相同的输入层和第一个密集层对象(model.layers[0] is model2.layers[0]和model.layers[1] is model2.layers[1])。
添加回答
举报
0/150
提交
取消