在Keras/TensorFlow中添加一个变量CNN致密层

问题描述:

我想知道是否有可能将变量添加到卷积神经网络的密集层中(以及来自先前卷积层的连接,还会有一个附加功能设置可用于歧视性目的)?如果这是可能的,任何人都可以给我一个例子/文件解释如何做到这一点?在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现在我已经添加了所需的架构! :) –

事实上,正如@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'。请参阅编辑:) –

好吧,假设你有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你能找到一个关于如何合并不同输入的例子。