2017-05-09 82 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)