Kerasで中間ノードの出力を確認する。
kerasのドキュメントのFAQに書かれているので、それ通りにやれば良い。一応、良くあるボストンの家の価格のデータの例を記載。
- そう言えば、kerasが終了時にsessionのdelに失敗する場合がある。ちゃんと、backendのclear_session()を呼ぶ。
import numpy import pandas from keras.models import Sequential, Model from keras.layers import Dense, Input from keras.callbacks import EarlyStopping import keras.backend as K # Prepare dataset df = pandas.read_csv("boston_house_price.csv", delim_whitespace=True, header=None) X = df.values[:, 0:13] Y = df.values[:, 13] def gen_model(): inputs = Input(shape=(13,), name='input_layer') x = Dense(13, activation='relu', name='1st_layer')(inputs) output = Dense(1, name='output_layer')(x) model = Model(inputs=inputs, outputs=output) model.compile(loss='mean_squared_error', optimizer='adam') return model model = gen_model() model.summary early_stopping = EarlyStopping(patience=5, verbose=1) model.fit(X, Y, batch_size=16, epochs=100, callbacks=[early_stopping], validation_split=0.1) # Intermediate Layer output intermediate_model = Model(inputs=model.input, outputs=model.get_layer('1st_layer').output) intermediate_output = intermediate_model.predict(X) print(intermediate_output) K.clear_session()