[英]How to get output of hidden layer given an input, weights and biases of the hidden layer in keras?
Suppose I have trained the model below for an epoch:假设我已经针对一个 epoch 训练了以下模型:
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'),
])
And I got the weights dense1_w
, biases dense1_b
of first hidden layer (named it dense1
) and a single data sample sample
.我得到了第一个隐藏层的权重dense1_w
、偏差dense1_b
(命名为dense1
)和单个数据样本sample
。
How do I use these to get the output of dense1
on the sample
in keras
?我如何使用这些来获得keras
sample
上的dense1
输出?
Thanks!谢谢!
The easiest way is to use the keras backend.最简单的方法是使用 keras 后端。 With the keras backend you can define a function that gives you the intermediate output of a keras model as defined here ( https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer ).使用 keras 后端,您可以定义一个函数,该函数为您提供此处定义的 keras 模型的中间输出( https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-中间层)。
So in essence:所以本质上:
get_1st_layer_output = K.function([model.layers[0].input],
[model.layers[1].output])
layer_output = get_1st_layer_output([X])
Just recreate the first part of the model up until the layer for which you would like the output (in your case only the first dense layer).只需重新创建模型的第一部分,直到您想要输出的层(在您的情况下只有第一个密集层)。 Afterwards you can load the trained weights of the first part in your newly created model and compile it.之后,您可以在新创建的模型中加载第一部分的训练权重并进行编译。
The output of the prediction with this new model will be the output of the layer (in your case the first dense layer).这个新模型的预测输出将是层的输出(在您的情况下是第一个密集层)。
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)
As for weights, I had a none-Sequential model.至于权重,我有一个非序列模型。 What I did was using model.summary()
to get the desired layers name and then model.get_layer("layer_name").get_weights()
to get the weights.我所做的是使用model.summary()
获取所需的图层名称,然后使用model.get_layer("layer_name").get_weights()
获取权重。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.