【问题标题】:Keras.layers.concatenate generates an error'Keras.layers.concatenate 生成错误'
【发布时间】:2019-02-19 00:57:51
【问题描述】:

我正在尝试训练具有两个输入分支的 CNN。这两个分支 (b1, b2) 将被合并成一个由 256 个神经元组成的密集连接层,dropout 率为 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'))

但是当我连接时它给了我以下错误:

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

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

但是我得到了'ImportError: cannot import name 'Merge''的错误。我正在使用 keras 2.2.2 和 python 3.6。

【问题讨论】:

  • 是的,我也试过了,但我得到了和以前一样的错误。而且我不确定如何将其更改为功能 API。我是 Keras 和机器学习的新手。
  • 啊哈!使用b1.outputb2.output 而不是b1b2
  • 我刚刚试了一下,现在出现以下错误:TypeError:添加的层必须是类Layer的实例。找到:Tensor("concatenate_1/concat:0", shape=(?, ?), dtype=float32)
  • 我不确定这是否会有所帮助。但是 xtest.shape[1] 是 5000 而 xtest.shape[2] 是 208。
  • 对不起!我最初的评论有点错误(因此我删除了它以防止进一步混淆)。请看我的回答。

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


【解决方案1】:

您需要使用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() 查看并重新检查模型的架构。

【讨论】:

  • 谢谢。我的网络现在工作正常。你为我节省了一天:)
猜你喜欢
  • 2020-06-08
  • 2015-03-12
  • 2018-12-05
  • 2014-05-23
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多