2017-05-09 30 views
1

假设我有训练低于模型划时代:如何在给定输入,隐藏层的权重和偏差的情况下获得隐藏层的输出?

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

谢谢!

回答

1

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

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

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)