Python 从Keras序列模型中提取子网络
我训练了一个非常简单的自动编码器网络,类似于此示例:Python 从Keras序列模型中提取子网络,python,tensorflow,Python,Tensorflow,我训练了一个非常简单的自动编码器网络,类似于此示例: import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential([ layers.Dense(128, activation="relu"), layers.Dense(64, activation="relu&quo
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Dense(128, activation="relu"),
layers.Dense(64, activation="relu"),
layers.Dense(32, activation="relu"),
layers.Dense(16, activation="relu"),
layers.Dense(8, activation="relu", name="latent_space"),
layers.Dense(16, activation="relu"),
layers.Dense(32, activation="relu", name="decode_32"),
layers.Dense(64, activation="relu"),
layers.Dense(128, activation="sigmoid"),
])
model.compile(...)
model.fit(...)
# Extract subnetwork here after training
我想知道是否有可能将数据馈送到潜在_空间
层,以便我可以随后从层解码_32
提取激活?理想情况下,我希望在训练后以潜在_空间
层作为输入层,以解码_32
层作为输出层,裁剪子网络。这可能吗?符合你的问题吗
def extract_layers(main_model, starting_layer_ix, ending_layer_ix) :
# create an empty model
new_model = Sequential()
for ix in range(starting_layer_ix, ending_layer_ix + 1):
curr_layer = main_model.get_layer(index=ix)
# copy this layer over to the new model
new_model.add(curr_layer)
return new_model
如果您喜欢使用第一层和最后一层的名称选择子网络,则该方法还具有层名称的参数,但更简单的解决方案是使用layer.name
参数检索要选择的层的索引
这样,您只需通过添加
layer_names = [layer.name for layer in main_model.layers]
starting_layer_ix = layer_names.index(starting_layer_name)
ending_layer_ix = layer_names.index(ending_layer_name)
应该返回new\u model
而不是未定义的变量您是对的,我在原始代码中没有看到这个错误。谢谢你的指点@RandomGuy也可以传递图层的名称,而不必知道图层的索引吗?我已经编辑了我的答案,希望它现在更适合你