从顺序 Keras 模型中保存特定层 [英] Saving the specific layer from within a sequential Keras model

查看:40
本文介绍了从顺序 Keras 模型中保存特定层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个自动编码器并训练模型,以便目标输出与输入相同.

I am building an auto-encoder and training the model so the targeted output is the same as the input.

我使用的是顺序 Keras 模型.当我使用 model.predict 时,我希望它从特定层(Dense256)而不是输出导出数组.

I am using a sequential Keras model. When I use model.predict I would like it to export the array from a specific layer (Dense256) not the output.

这是我目前的模型:

model = Sequential()
model.add(Dense(4096, input_dim = x.shape[1], activation = 'relu'))
model.add(Dense(2048, activation='relu'))
model.add(Dense(1024, activation='relu'))
model.add(Dense(512, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(512, activation='relu'))
model.add(Dense(1024, activation='relu'))
model.add(Dense(2048, activation='relu'))
model.add(Dense(4096, activation='relu'))
model.add(Dense(x.shape[1], activation ='sigmoid'))
model.compile(loss = 'mean_squared_error', optimizer = 'adam')
history = model.fit(data_train,data_train,
                    verbose=1,
                    epochs=10, 
                    batch_size=256,
                    shuffle=True,
                    validation_data=(data_test, data_test))

推荐答案

训练后,从训练好的模型 (model) 中创建一个新模型 (model2),以您想要的层结尾.

After training, create a new model (model2) from your trained model (model) ending in your desired layer.

您可以使用图层名称执行此操作:

You can do so either with layer name:

(在model.summary() 中,你的dense 层'name' 有256 个神经元是dense_5)

(In model.summary(), your dense's layer 'name' with 256 neurons is dense_5)

from keras.models import Model
model2= Model(model.input,model.get_layer('dense_5').output)

或按层顺序:

(您的具有 256 个神经元的密集层在 model.summary() 中排名第五)

(your dense layer with 256 neurons is fifth in model.summary())

from keras.models import Model
model2= Model(model.input,model.layers[4].output)

然后你可以使用预测

preds=model2.predict(x)

这篇关于从顺序 Keras 模型中保存特定层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆