python - 修改 Keras 模型最有效的方法是什么?

标签 python tensorflow keras

有没有办法将节点添加到现有 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)

请注意,在这种情况下,modelmodel2 共享相同的输入层和第一个密集层对象(model.layers[0] 是 model2.layers[ 0]model.layers[1] 是 model2.layers[1])。

关于python - 修改 Keras 模型最有效的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63337839/

相关文章:

python - 为什么 TF Keras 推理比 Numpy 运算慢得多?

python - 分类 : What happens if one class has 4 times as much data as the other class?

python - 计算 Nash-Sutcliffe 效率

python - 在 Keras 中制作采样层

python - 在 slim 的tensorflow和tf记录批处理中微调inceptionv3的问题

python - 如何将从 image_dataset_from_directory 获取的数据集拆分为数据和标签?

tensorflow - 为什么同一个数据集使用tensorflow2.0训练准确率和验证准确率不一样?

python - 我怎样才能获得有关恢复维基页面编辑的详细信息?

python - Scikit-learn 中仅针对 DataFrame 的一部分进行 One-Hot 编码

python - 选择特定行的 2D PyTorch 张量