2017-03-02 95 views
4

我想知道是否有可能將變量添加到卷積神經網絡的密集層中(以及來自先前卷積層的連接,還會有一個附加功能設置可用於歧視性目的)?如果這是可能的,任何人都可以給我一個例子/文件解釋如何做到這一點?在Keras/TensorFlow中添加一個變量CNN緻密層

我希望能夠使用Keras,但如果Keras太嚴格,我很樂意使用TensorFlow。

編輯:在這種情況下,我認爲這應該工作的方式是,我提供了一個包含圖像和相關功能集到神經網絡(以及在訓練相關分類期間)的列表。

EDIT2:我需要的架構看起來像:

   ___________  _________  _________  _________  ________ ______ 
       | Conv |  | Max |  | Conv |  | Max | |  | |  | 
    Image --> | Layer 1 | --> | Pool 1 | --> | Layer 2 | --> | Pool 2 | -->|  | |  | 
       |_________|  |________|  |_________|  |________| | Dense | | Out | 
                      | Layer |-->|_____| 
    Other  ------------------------------------------------------------>|  | 
    Data                 |  | 
                      |_______| 
+0

您正在嘗試構建的架構是什麼?我不確定要理解你的問題 –

+0

@NassimBen現在我已經添加了所需的架構! :) –

回答

3

事實上,正如@Marcin所說,你可以使用合併層。

我建議你爲此使用Functionnal API。如果您不熟悉它,請閱讀some doc here

下面是使用keras API您亂畫網絡模式:

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

# this is your image input definition. You have to specify a shape. 
image_input = Input(shape=(32,32,3)) 
# Some more data input with 10 features (eg.) 
other_data_input = Input(shape=(10,))  

# First convolution filled with random parameters for the example 
conv1 = Convolution2D(nb_filter = nb_filter1, nb_row = nb_row1, nb_col=_nb_col1, padding = "same", activation = "tanh")(image_input) 
# MaxPool it 
conv1 = MaxPooling2D(pool_size=(pool_1,pool_2))(conv1) 
# Second Convolution 
conv2 = Convolution2D(nb_filter = nb_filter2, nb_row = nb_row2, nb_col=_nb_col2, padding = "same", activation = "tanh")(conv1) 
# MaxPool it 
conv2 = MaxPooling2D(pool_size=(pool_1,pool_2))(conv2) 
# Flatten the output to enable the merge to happen with the other input 
first_part_output = Flatten()(conv2) 

# Merge the output of the convNet with your added features by concatenation 
merged_model = keras.layers.concatenate([first_part_output, other_data_input]) 

# Predict on the output (say you want a binary classification) 
predictions = Dense(1, activation ='sigmoid')(merged_model) 

# Now create the model 
model = Model(inputs=[image_input, other_data_input], outputs=predictions) 
# see your model 
model.summary() 

# compile it 
model.compile(optimizer='adamax', loss='binary_crossentropy') 

你去那裏:)這到底是很容易的,定義要多少投入和產出,只需指定它們在列表中當您創建Model對象時。當你適應它時,也將它們單獨送入列表中。

+0

非常感謝你;這非常有幫助! –

+0

使用'.fit'訓練這個模型時,損失在所有時代都保持不變?你有什麼想法,爲什麼這可能是? –

+0

我會編輯,錯誤來自最後一層的激活。在1個輸出上使用sigmoid或在2個輸出上使用'softmax'。請參閱編輯:) –

1

好吧,假設你有convoluton_model,你可以以下面的方式做到這一點:

convolution_model = Flatten()(convolution_model) # if it wasn't flattened before 
static_features_input = Input(shape=(static_features_size,)) 
blended_features = merge([convolution_model, static_features_input], mode='concat') 
... here you are defining a blending model with blended features as input 

Here你能找到一個關於如何合併不同輸入的例子。