gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:46:15 24 4
gpt4 key购买 nike

我正在尝试训练具有两个输入分支的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com