2017-06-28 15 views
1

深い畳み込みNNと2つの画像を比較したいとします。ケラスで同じカーネルで2つの異なる経路を実装するにはどうすればよいですか?このようケラスの層間で畳み込みカーネルを共有するにはどうすればよいですか?

enter image description here

私は、畳み込み層に1,2および3の使用を必要とし、同じカーネルを訓練します。

可能ですか?

私も

enter image description here

以下のような画像を連結するために考えていたが、問題は、最初の画像の上にtolopologyを実装する方法についてです。

答えて

4

あなたはnodesを作成し、モデルに二回同じ層を使用することができます。

from keras.models import Model  
from keras.layers import * 

#create the shared layers 
layer1 = Conv2D(filters, kernel_size.....) 
layer2 = Conv2D(...)  
layer3 = .... 

#create one input tensor for each side 
input1 = Input((imageX, imageY, channels)) 
input2 = Input((imageX, imageY, channels)) 

#use the layers in side 1 
out1 = layer1(input1) 
out1 = layer2(out1) 
out1 = layer3(out1) 

#use the layers in side 2 
out2 = layer1(input2) 
out2 = layer2(out2) 
out2 = layer3(out2) 

#concatenate and add the fully connected layers 
out = Concatenate()([out1,out2]) 
out = Flatten()(out) 
out = Dense(...)(out) 
out = Dense(...)(out) 

#create the model taking 2 inputs with one output 
model = Model([input1,input2],out) 

あなたはまた、より大きな1のサブモデル作り、二度を同じモデルを使用することができます。

#have a previously prepared model 
convModel = some model previously prepared 

#define two different inputs 
input1 = Input((imageX, imageY, channels)) 
input2 = Input((imageX, imageY, channels)) 

#use the model to get two different outputs: 
out1 = convModel(input1) 
out2 = convModel(input2) 

#concatenate the outputs and add the final part of your model: 
out = Concatenate()([out1,out2]) 
out = Flatten()(out) 
out = Dense(...)(out) 
out = Dense(...)(out) 

#create the model taking 2 inputs with one output 
model = Model([input1,input2],out) 
+0

あなたはそれに応じて訓練するだろうか?グラデーションは正しく認識されますか? – Dims

+0

はい、Kerasには「ノード」という概念があり、入力テンソルをレイヤーに渡すときにのみ作成されます。複数回実行すると、レイヤーには多くのノードが割り当てられます。そして、もしあなたが 'layer [i] .output'を実行するのではなく、その層の出力を望むなら、' layer [i] .get_output_at(node_index) 'を使い始めます。 –

+0

私はちょうどこのコードを使用して両方を一緒に分類するために同時に2つのイメージを取る小さなMNISTモデルをテストしました。それは素晴らしい仕事:) –

2

実際に同じ(インスタンスの)レイヤーを2回使用すると、ウェイトが確実に共有されます。

だけ例を示すモデルからsiamese example、私はちょうどここに置くの抜粋を見て:

# because we re-use the same instance `base_network`, 
# the weights of the network 
# will be shared across the two branches 
processed_a = base_network(input_a) 
processed_b = base_network(input_b) 
関連する問題