Keras Sequential模型中Flatten层的作用是什么?
What Does the Flatten Layer Do in Keras Sequential Models?
Hey there! Let's break down the Flatten layer's role—it's a straightforward but essential component, especially when you're building models for spatial data like images.
Core Purpose: Bridge Spatial Layers and Dense Layers
Think of it as a translator between two different "dialects" of data:
- Layers like
Conv2DorMaxPooling2Doutput multidimensional tensors (e.g.,(batch_size, height, width, channels)for images). These tensors keep spatial structure intact, which is great for detecting patterns like edges or textures. - But
Dense(fully connected) layers only understand 1D feature vectors—they can't process 2D/3D spatial data directly.
The Flatten layer solves this by taking your multidimensional input and stretching it into a single dimension (while keeping the batch size intact). It doesn't modify the actual data values—it just rearranges their shape.
Example in Action
Let's say you're working with MNIST images (28x28 grayscale):
- After a convolution and pooling step, your model outputs a tensor with shape
(64, 14, 14, 32)—that's 64 samples, each with a 14x14 grid of 32 feature channels. - Passing this through a Flatten layer converts it to
(64, 6272)(since 141432 = 6272). Now each sample is a 1D vector that yourDenselayers can process.
Here's a quick code snippet to see it in context:
from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense model = Sequential([ # Input: 28x28 grayscale images Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)), MaxPooling2D((2,2)), # Reduces spatial size to 14x14 Flatten(), # Reshapes to (None, 6272) Dense(64, activation='relu'), Dense(10, activation='softmax') # Output 10 MNIST classes ])
Key Notes
- No trainable parameters: Unlike convolution or dense layers, Flatten doesn't learn anything—it's just a shape transformation tool.
- Preserves batch integrity: The first dimension (batch size) always stays the same—each sample in the batch is flattened independently.
内容的提问来源于stack exchange,提问作者james james
相关产品推荐
相关产品推荐

