如何用卷积层代替稠密层?

时间:2018-09-17 17:29:29

标签: python keras keras-layer

我想用卷积层替换Dense_out层,有人可以告诉我该怎么做吗?

代码:

model = Sequential()
conv_1 = Conv2D(filters = 32,kernel_size=(3,3),activation='relu')
model.add(conv_1)
conv_2 = Conv2D(filters=64,kernel_size=(3,3),activation='relu')
model.add(conv_2)
pool = MaxPool2D(pool_size = (2,2),strides = (2,2), padding = 'same')
model.add(pool)
drop = Dropout(0.5)
model.add(drop)
model.add(Flatten())
Dense_1 = Dense(128,activation = 'relu')
model.add(Dense_1)
Dense_out = Dense(57,activation = 'softmax')
model.add(Dense_out)
model.compile(optimizer='Adam',loss='categorical_crossentropy',metric=['accuracy'])
model.fit(train_image,train_label,epochs=10,verbose = 1,validation_data=(test_image,test_label))
print(model.summary())

当我尝试此代码时:

model = Sequential()
conv_01 = Conv2D(filters = 32,kernel_size=(3,3),activation='relu')
model.add(conv_01)
conv_02 = Conv2D(filters=64,kernel_size=(3,3),activation='relu')
model.add(conv_02)
pool = MaxPool2D(pool_size = (2,2),strides = (2,2), padding = 'same')
model.add(pool)
conv_11 = Conv2D(filters=64,kernel_size=(3,3),activation='relu')
model.add(conv_11)
pool_2 = MaxPool2D(pool_size=(2,2),strides=(2,2),padding='same')
model.add(pool_2)
drop = Dropout(0.3)
model.add(drop)
model.add(Flatten())
Dense_1 = Dense(128,activation = 'relu')
model.add(Dense_1)
Dense_2 = Dense(64,activation = 'relu')
model.add(Dense_2)
conv_out = Conv2D(filters= 64,kernel_size=(3,3),activation='relu')
model.add(Dense_out)
model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(train_image,train_label,epochs=10,verbose = 1,validation_data=(test_image,test_label))

我收到以下错误

  

ValueError:conv2d_3层的输入0与该层不兼容:   预期ndim = 4,找到的ndim = 2。收到完整的图形:[无,64]

我是新来的,所以解释会很有帮助

1 个答案:

答案 0 :(得分:0)

您将需要重塑形状,以便能够根据需要在conv2D图层中使用2x2滤镜。 您可以使用:

out = keras.layers.Reshape(target_shape)
model.add(out)

然后进行卷积:

conv_out = Conv2D(filters=3,kernel_size=(3,3),activation='softmax')
model.add(conv_out)

其中filters是您要在输出层中使用的通道数(RGB为3)。

有关Keras Documentation中的图层和参数的更多信息