【问题标题】:Keras get the output of the last layer during trainingKeras在训练时得到最后一层的输出
【发布时间】:2020-05-04 16:47:58
【问题描述】:

目标是在训练阶段恢复变分自动编码器最后一层的输出,用作另一种算法的训练数据。 附上模型变分自编码器代码:

encoding_dim=58
input_dim=xtrain.shape[1]
inputArray=Input(shape=(input_dim,))
encoded= Dense(units=encoding_dim,activation="tanh")(inputArray) 
encoded= Dense(units=29,activation="tanh")(encoded)
encoded= Dense(units=15,activation="tanh")(encoded)
encoded= Dense(units=10,activation="tanh")(encoded)
encoded= Dense(units=3,activation="tanh")(encoded)
encoded= Dense(units=10,activation="tanh")(encoded)
decoded= Dense(units=15,activation="tanh")(encoded)
decoded= Dense(units=29,activation="tanh")(decoded)
decoded= Dense(units=encoding_dim,activation="tanh")(decoded)
decoded= Dense(units=input_dim,activation="sigmoid")(decoded) 
autoecoder=Model(inputArray,decoded)
autoecoder.summary()

autoecoder.compile(optimizer=RMSprop(),loss="mean_squared_error",metrics=["mae"])
#hyperparametrs :
batchsize=100
epoch=10
history = autoecoder.fit(xtrain_noise,xtrain,
              batch_size=batchsize,
              epochs=epoch,
              verbose=1,
              shuffle=True,
              validation_data=(xtest_noise,xtest),
              callbacks=[TensorBoard(log_dir="../logs/DenoiseautoencoderHoussem")])

我发现我可以按如下方式检索所需的图层:

autoecoder.layers[10].output

但是我如何将他在训练期间的输出存储在一个列表中?谢谢。

编辑: 我可以通过在 xtrain 数据上使用模型的预测方法来做到这一点,但我认为这不是最好的方法。

【问题讨论】:

    标签: keras deep-learning autoencoder


    【解决方案1】:

    您可以使用先前训练的模型的预测来训练新模型,只需在所需的输出新层上堆叠并在旧层上设置 trainable = False。这是一个虚拟的例子

    # after autoencoder fitting
    
    for i,l in enumerate(autoecoder.layers):
        autoecoder.layers[i].trainable = False
        print(l.name, l.trainable)
    
    output_autoecoder = autoecoder.layers[10].output
    x_new = Dense(32, activation='relu')(output_autoecoder) # add a new layer for exemple
    
    new_model = Model(autoecoder.input, x_new)
    new_model.compile('adam', 'mse')
    new_model.summary()
    

    我使用最后一个自动编码器层的输出作为新块的输入。我们可以合并所有编译一个输入与自动编码器相同的新模型,这样我们就可以将训练数据用于另一个算法,而无需调用预测方法

    【讨论】:

    • 感谢@marco,如果我尝试使用自动编码器的输出作为另一个 DL 算法的输入,这是一个很好的解决方案,但在我的情况下,输出将是 xgboost 的训练数据集跨度>
    • 这样,预测方法是唯一可用的解决方案...如果您认为此答案有价值,请不要忘记接受它作为答案或投票
    【解决方案2】:

    要解决这个问题,唯一可以使用的解决方案是DL模型的.predict方法。谢谢@marrco

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 2017-10-07
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多