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

时间:2017-05-09 13:25:59

标签: python tensorflow keras neural-network deep-learning

假设我已经训练了以下模型的时代:

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'),
])

我得到了权重dense1_w,第一个隐藏图层(名为dense1_b)的偏差dense1和单个数据样本sample

如何使用这些来获取dense1 samplekeras的输出?

谢谢!

3 个答案:

答案 0 :(得分:11)

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

所以实质上:

int index = abc.indexOf("def");
if (index == -1) {
    index = abc.indexOf("ghi");
} else {
    // something else
}

答案 1 :(得分:5)

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

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

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)

答案 2 :(得分:0)

关于权重,我有一个非顺序模型。我所做的是使用model.summary()获取所需的图层名称,然后使用model.get_layer("layer_name").get_weights()获取权重。

相关问题