如何从预训练的 TensorFlow 模型中删除图层?

How to remove layer from pre-trained TensorFlow model?

我在 TensorFlow 中用三个隐藏层训练了以下模型:

inputs = tf.keras.Input(shape=(timesteps, feature_size))

l = LSTM(units=state_size,
               return_sequences=True)(inputs)
l = LSTM(units=state_size,
               return_sequences=True)(l)
l = LSTM(units=state_size,
               return_sequences=True)(l)

output = TimeDistributed(Dense(output_size, activation='softmax'))(l)

model = tf.keras.Model(inputs=inputs, outputs=output)

现在,我想使用该模型但跳过第二个隐藏层,即直接将第一层的输出传递到第三层而不经过第二层。 我知道我可以通过以下方式获取第一层的输出:

output = model.layers[idx].Output

但是我现在如何将这个输出提供给第三层呢? 非常感谢您的帮助!

一种方法是使用图层名称来创建新模型。

下面的示例使用指定的名称。您也可以使用 Keras 提供的默认名称。

inputs = tf.keras.Input(shape=(timesteps, feature_size))

l = LSTM(units=state_size, return_sequences=True, name="lstm1")(inputs)
l = LSTM(units=state_size, return_sequences=True, name="lstm2")(l)
l = LSTM(units=state_size, return_sequences=True, name="lstm3")(l)

output = TimeDistributed(Dense(output_size, activation='softmax'))(l)

model = tf.keras.Model(inputs=inputs, outputs=output)

# Now create the second model using specific layers from the first model
reuse_layers = ["lstm1", "lstm3"]

inputs = tf.keras.Input(shape=(timesteps, feature_size))
l = inputs
for layer_name in reuse_layers:
    l = model.get_layer(layer_name)(l)

output = TimeDistributed(Dense(output_size, activation='softmax'))(l)
new_model = Model(inputs=inputs, outputs=output)