如何在keras中给出隐藏层的输入,权重和偏差来获取隐藏层的输出?

Dan*_*iel 7 python neural-network deep-learning keras tensorflow

假设我已经训练了下面的模型一个时代:

model = Sequential([
    Dense(32, input_dim=784), # first number is output_dim
    Activation('relu'),
    Dense(10), # output_dim, input_dim is taken for granted from above
    Activation('softmax'),
])
Run Code Online (Sandbox Code Playgroud)

我得到了第一个隐藏层(命名为)的权重dense1_w,偏差和单个数据样本.dense1_bdense1sample

如何使用这些得到的输出dense1samplekeras

谢谢!

Tho*_*etz 14

最简单的方法是使用keras后端.使用keras后端,您可以定义一个函数,为您提供此处定义的keras模型的中间输出(https://keras.io/getting-started/faq/#how-can-i-obtain-the-output- - 中间层).

所以本质上:

get_1st_layer_output = K.function([model.layers[0].input],
                                  [model.layers[1].output])
layer_output = get_1st_layer_output([X])
Run Code Online (Sandbox Code Playgroud)


Wil*_*ren 6

只需重新创建模型的第一部分,直到需要输出的图层(在您的情况下,仅是第一密集层)即可。然后,您可以在新创建的模型中加载训练后的第一部分的权重并进行编译。

这个新模型的预测输出将是该层的输出(在您的情况下是第一个密集层)。

from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np

model = Sequential([
    Dense(32, input_dim=784), # first number is output_dim
    Activation('relu'),
    Dense(10), # output_dim, input_dim is taken for granted from above
    Activation('softmax'),
])
model.compile(optimizer='adam', loss='categorical_crossentropy')

#create some random data
n_features = 5
samples = np.random.randint(0, 10, 784*n_features).reshape(-1,784)
labels = np.arange(10*n_features).reshape(-1, 10)

#train your sample model
model.fit(samples, labels)

#create new model
new_model= Sequential([
    Dense(32, input_dim=784), # first number is output_dim
    Activation('relu')])

#set weights of the first layer
new_model.set_weights(model.layers[0].get_weights())

#compile it after setting the weights
new_model.compile(optimizer='adam', loss='categorical_crossentropy')

#get output of the first dens layer
output = new_model.predict(samples)
Run Code Online (Sandbox Code Playgroud)