2017-05-09 8 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という名前の)最初の隠れ層と、単一のデータサンプルsampledense1_bにバイアスをかけます。

sampledense1の出力をkerasにするにはどうすればよいですか?

ありがとうございます!

答えて

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) 
2

最も簡単な方法はケラスバックエンドを使用することです。ケラスバックエンドを使用すると、ここで定義したケラスモデル(https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer)の中間出力を与える関数を定義できます。本質的にはそう

get_1st_layer_output = K.function([model.layers[0].input], 
            [model.layers[1].output]) 
layer_output = get_1st_layer_output([X]) 
関連する問題