Kerasシーケンシャルモデルからサブネットワークを抽出する
Aug 24 2020
この例のような非常に単純なオートエンコーダネットワークをトレーニングしました。
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Dense(128, activation="relu"),
layers.Dense(64, activation="relu"),
layers.Dense(32, activation="relu"),
layers.Dense(16, activation="relu"),
layers.Dense(8, activation="relu", name="latent_space"),
layers.Dense(16, activation="relu"),
layers.Dense(32, activation="relu", name="decode_32"),
layers.Dense(64, activation="relu"),
layers.Dense(128, activation="sigmoid"),
])
model.compile(...)
model.fit(...)
# Extract subnetwork here after training
latent_space
後でレイヤーからアクティベーションを抽出できるように、データをレイヤーにフィードできるかどうか知りたいdecode_32
ですか?理想的にはcrop
、latent_space
レイヤーを入力decode_32
として、レイヤーを出力レイヤーとしてトレーニングした後、サブネットワークを作成したいと思います。それは可能ですか?
回答
1 RandomGuy Aug 24 2020 at 03:02
この答えは、あなたの質問に合いますか?
def extract_layers(main_model, starting_layer_ix, ending_layer_ix) :
# create an empty model
new_model = Sequential()
for ix in range(starting_layer_ix, ending_layer_ix + 1):
curr_layer = main_model.get_layer(index=ix)
# copy this layer over to the new model
new_model.add(curr_layer)
return new_model
最初と最後のレイヤーの名前でサブネットワークを選択する場合は、get_layerメソッドにもレイヤー名の引数がありますが、引数のおかげで選択するレイヤーのインデックスを取得するのがより簡単な解決策になりlayer.name
ます。
そうすれば、追加して前の関数を変更するだけです。
layer_names = [layer.name for layer in main_model.layers]
starting_layer_ix = layer_names.index(starting_layer_name)
ending_layer_ix = layer_names.index(ending_layer_name)