Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从Keras序列模型中提取子网络_Python_Tensorflow - Fatal编程技术网

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也可以传递图层的名称,而不必知道图层的索引吗?我已经编辑了我的答案,希望它现在更适合你