python - Keras.layers.concatenate 生成错误'

标签 python machine-learning keras conv-neural-network

我正在尝试训练具有两个输入分支的 CNN。这两个分支(b1,b2)将被合并成一个由 256 个神经元组成的密集连接层,丢失率为 0.25。这是我到目前为止所拥有的:

batch_size, epochs = 32, 3
ksize = 2
l2_lambda = 0.0001


### My first model(b1)
b1 = Sequential()
b1.add(Conv1D(128*2, kernel_size=ksize,
             activation='relu',
             input_shape=( xtest.shape[1], xtest.shape[2]),
             kernel_regularizer=keras.regularizers.l2(l2_lambda)))
b1.add(Conv1D(128*2, kernel_size=ksize, activation='relu',kernel_regularizer=keras.regularizers.l2(l2_lambda)))
b1.add(MaxPooling1D(pool_size=ksize))
b1.add(Dropout(0.2))

b1.add(Conv1D(128*2, kernel_size=ksize, activation='relu',kernel_regularizer=keras.regularizers.l2(l2_lambda)))
b1.add(MaxPooling1D(pool_size=ksize))
b1.add(Dropout(0.2))

b1.add(Flatten())

###My second model (b2)

b2 = Sequential()
b2.add(Dense(64, input_shape = (5000,), activation='relu',kernel_regularizer=keras.regularizers.l2(l2_lambda)))
b2.add(Dropout(0.1))


##Merging the two models
model = Sequential()
model.add(concatenate([b1, b2],axis = -1))
model.add(Dense(256, activation='relu', kernel_initializer='normal',kernel_regularizer=keras.regularizers.l2(l2_lambda)))
model.add(Dropout(0.25))
model.add(Dense(num_classes, activation='softmax'))

但是当我连接时出现以下错误:

enter image description here

我首先尝试使用以下命令:

  model.add(Merge([b1, b2], mode = 'concat'))

但我收到错误“ImportError:无法导入名称“Merge””。我使用的是 keras 2.2.2 和 python 3.6。

最佳答案

您需要使用functional API实现您想要的目标。您可以使用 Concatenate 层或其等效的功能 API concatenate:

concat = Concatenate(axis=-1)([b1.output, b2.output])
# or you can use the functional api as follows:
#concat = concatenate([b1.output, b2.output], axis=-1)

x = Dense(256, activation='relu', kernel_initializer='normal',
          kernel_regularizer=keras.regularizers.l2(l2_lambda))(concat)
x = Dropout(0.25)(x)
output = Dense(num_classes, activation='softmax')(x)

model = Model([b1.input, b2.input], [output])

请注意,我仅将模型的最后一部分转换为函数形式。您可以对其他两个模型 b1b2 执行相同的操作(实际上,您尝试定义的架构似乎是一个由两个分支组成的单一模型合并在一起)。最后,使用 model.summary() 查看并重新检查模型的架构。

关于python - Keras.layers.concatenate 生成错误',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52328130/

相关文章:

python - 在命令行中运行带有别名的 python 命令,如 npm

python - 如何解释多类分类的输出?

image-processing - 小图像数据集的数据增强技术?

deep-learning - 如何在keras中将一层上采样到任何大小?

Python 跨平台

python - 在 tkinter 中创建 n 个窗口

python - 在 Keras/TensorFlow 中使用纯 numpy 指标作为指标

keras - 在 Keras 中 weight_regularizer 和 activity_regularizer 有什么区别

python - 如何限制多处理进程的范围?

machine-learning - 为什么在机器学习问题中需要使用正则化?