gpt4 book ai didi

python - 使用 Sequential API 从 Keras 自动编码器中提取编码/解码模型

转载 作者:行者123 更新时间:2023-11-30 09:05:12 24 4
gpt4 key购买 nike

我正在训练一个使用 Keras 中的 Sequential API 构建的自动编码器。我想创建实现编码和解码功能的单独模型。我从examples知道如何使用函数式 API 执行此操作,但我找不到如何使用顺序 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.

最佳答案

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

decoder.build(input_shape=(None, encoding_dim))   # note that batch axis must be included
<小时/>

顺便说一句,不需要在 model.summary() 上调用 print,因为它会自行打印结果。

关于python - 使用 Sequential API 从 Keras 自动编码器中提取编码/解码模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53843573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com