有没有办法将节点添加到现有 Keras 模型中的层?如果是这样,最有效的方法是什么?
此外,是否可以通过图层执行相同的操作?即向现有 Keras 模型添加一个新层(例如,在输入层之后)。
我知道的一种方法是通过迭代和克隆模型的每一层来使用 Keras 功能 API,以便创建具有所需更改的原始模型的“副本”,但这是否是实现此目的的最有效方法任务?
最佳答案
您可以获取模型中某个层的输出,并从该层开始构建另一个模型:
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] 是 model2.layers[ 0]
和 model.layers[1] 是 model2.layers[1]
)。
关于python - 修改 Keras 模型最有效的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63337839/