How does data shape change during Conv2D and Dense in Keras?

一曲冷凌霜 提交于 2019-12-03 08:05:41

According to keras doc,

Conv2D Output shape

4D tensor with shape: (samples, filters, new_rows, new_cols) if data_format='channels_first' or 4D tensor with shape: (samples, new_rows, new_cols, filters) if data_format='channels_last'. rows and cols values might have changed due to padding.

Since you are using channels_last, the shape of layer output would be:

# shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Flatten()(x)
# shape=(100, row*col*32)    

x = Dense(256, activation='relu')(x)
# shape=(100, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, 10)

Error explanation (edited, thanks to @Marcin)

Linking a 4D tensor (shape=(100, row, col, 32)) to a 2D one (shape=(100, 256)) using Dense layer will still form a 4D tensor (shape=(100, row, col, 256)) which is not what you want.

# shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Dense(256, activation='relu')(x)
# shape=(100, row, col, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, row, col, 10)

And the error will occur when the mismatch between output 4D tensor and target 2D tensor happens.

That's why you need a Flatten layer to flat it from 4D to 2D.

Reference

Conv2D Dense

From Dense documentation one may read that in case when an input to a Dense has more than two dimensions - it's applied only to a last one - and all other dimensions are kept:

# shape=(100, 100, 100, 3)

x = Conv2D(32, (3, 3), activation='relu')(input_layer)
# shape=(100, row, col, 32)

x = Dense(256, activation='relu')(x)
# shape=(100, row, col, 256)

x = Dense(10, activation='softmax')(x)
# shape=(100, row, col, 10)

That's why a 4d target is expected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!