【问题标题】:How to get output from a specific layer in keras.tf, the bottleneck layer in autoencoder?如何从自动编码器中的瓶颈层 keras.tf 中的特定层获取输出?
【发布时间】:2020-01-12 11:51:11
【问题描述】:

我正在开发一种自动编码器,用于对某些图像组进行聚类。

input_images->...->bottleneck->...->output_images

我已将自动编码器校准至满意并保存了模型;一切都是在 python3 上使用 keras.tensorflow 开发的。

下一步是将自动编码器应用于大量图像,并根据瓶颈层中的余弦距离对它们进行聚类。糟糕,我刚刚意识到我不知道 keras.tf 中用于将模型批量运行到特定层而不是输出层的语法。因此问题:

我如何将Model.predict_on_batchModel.predict_generator 之类的东西运行到某个“瓶颈”层并检索该层上的值而不是输出层上的值?

【问题讨论】:

    标签: tensorflow keras autoencoder


    【解决方案1】:

    您需要定义一个新模型(如果您最初没有将编码器和解码器定义为单独的模型,这通常是最简单的选择)。

    如果你的模型是在没有重用层的情况下定义的,那就是:

    inputs = model.input   
    outputs= model.get_layer('bottleneck').output
    
    encoder = Model(inputs, outputs)
    

    encoder 模型用作任何其他模型。

    【讨论】:

      【解决方案2】:

      完整的代码是这样的,

      # ENCODER
      encoding_dim = 37310
      
      input_layer = Input(shape=(encoding_dim,))
      
      encoder = Dense(500, activation='tanh')(input_layer)
      encoder = Dense(100, activation='tanh')(encoder)
      encoder = Dense(50, activation='tanh', name='bottleneck_layer')(encoder)
      
      decoder = Dense(100, activation='tanh')(encoder)
      decoder = Dense(500, activation='tanh')(decoder)
      decoder = Dense(37310, activation='sigmoid')(decoder)
      
      # full model
      model_full = models.Model(input_layer, decoder)
      model_full.compile(optimizer='adam', loss='mse')
      model_full.fit(x, y, epochs=20, batch_size=16)
      
      # bottleneck model
      bottleneck_output = model_full.get_layer('bottleneck_layer').output
      model_bottleneck = models.Model(inputs = model_full.input, outputs = bottleneck_output)
      
      bottleneck_predictions = model_bottleneck.predict(X_test)
      

      【讨论】:

        猜你喜欢
        • 2021-01-07
        • 1970-01-01
        • 2018-10-15
        • 1970-01-01
        • 2021-05-08
        • 1970-01-01
        • 2021-04-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多