【问题标题】:Extracting encoding/decoding models from Keras autoencoder using Sequential API使用 Sequential API 从 Keras 自动编码器中提取编码/解码模型
【发布时间】:2019-05-19 11:50:30
【问题描述】:

我正在训练使用 Keras 中的 Sequential API 构建的自动编码器。我想创建单独的模型来实现编码和解码功能。我从examples 知道如何使用功能 API 执行此操作,但我找不到如何使用 Sequential API 完成此操作的示例。以下示例代码是我的起点:

input_dim = 2904
encoding_dim = 4
hidden_dim = 128

# instantiate model
autoencoder = Sequential()

# 1st hidden layer    
autoencoder.add(Dense(hidden_dim, input_dim=input_dim, use_bias=False))
autoencoder.add(BatchNormalization())
autoencoder.add(Activation('elu'))
autoencoder.add(Dropout(0.5))

# encoding layer    
autoencoder.add(Dense(encoding_dim, use_bias=False))
autoencoder.add(BatchNormalization())
autoencoder.add(Activation('elu'))
# autoencoder.add(Dropout(0.5))

# 2nd hidden layer    
autoencoder.add(Dense(hidden_dim, use_bias=False))
autoencoder.add(BatchNormalization())
autoencoder.add(Activation('elu'))
autoencoder.add(Dropout(0.5))

# output layer
autoencoder.add(Dense(input_dim))

我意识到我可以使用autoencoder.layer[i] 选择单个图层,但我不知道如何将新模型与一系列此类图层相关联。我天真地尝试了以下方法:

encoder = Sequential()
for i in range(0,7):
    encoder.add(autoencoder.layers[i])

decoder = Sequential()
for i in range(7,12):
    decoder.add(autoencoder.layers[i])


print(encoder.summary())
print(decoder.summary())

这似乎适用于编码器部分(显示了有效的摘要),但解码器部分产生了错误:

This model has not yet been built. Build the model first by calling build() or calling fit() with some data. Or specify input_shape or batch_input_shape in the first layer for automatic build.

【问题讨论】:

    标签: python machine-learning keras keras-layer autoencoder


    【解决方案1】:

    由于没有明确设置中间层的输入形状(即这里我指的是autoencoder.layers[7]),当您将其作为第一层添加到另一个模型时,该模型不会自动构建(即构建过程涉及为模型中的层构建权重张量)。因此,您需要显式调用build 方法并设置输入形状:

    decoder.build(input_shape=(None, encoding_dim))   # note that batch axis must be included
    

    附带说明,无需在model.summary() 上调用print,因为它会自行打印结果。

    【讨论】:

    • 所以中间层显然没有在内部保留上一层输出维度的知识?这样就可以解释了——谢谢。
    【解决方案2】:

    另一种方法也有效。

    input_img = Input(shape=(encoding_dim,))
    previous_layer = input_img
    for i in range(bottleneck_layer,len(autoencoder.layers)): # bottleneck_layer = index of bottleneck_layer + 1!
        next_layer = autoencoder.layers[i](previous_layer)
        previous_layer = next_layer
    decoder = Model(input_img, next_layer)
    

    【讨论】:

      猜你喜欢
      • 2019-08-22
      • 1970-01-01
      • 2019-09-13
      • 2019-06-14
      • 2019-07-22
      • 2019-02-15
      • 2019-01-05
      • 1970-01-01
      • 2017-07-19
      相关资源
      最近更新 更多