You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow中Fashion MNIST模型Flatten层形状及图像使用时机疑问

关于Fashion MNIST模型中Flatten层形状及图像使用阶段的疑问

问题描述

使用TensorFlow中的Fashion MNIST数据集构建如下模型时,为何Flatten层的形状仅为(28*28=784)而非784×60000?60000为数据集中的图像数量。此外,每个图像在模型中的哪个阶段被使用?

# flatten the images into a 1D array
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation=tf.nn.relu),
    tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

# Get the input shape of the Flatten layer
input_shape = model.layers[0].input_shape
print("Input shape:", input_shape)

# Get the output shape of the Flatten layer
output_shape = model.layers[0].output_shape
print("Output shape:", output_shape)

问题解答

1. 为什么Flatten层的形状是784而非784×60000?

  • Keras模型定义时的input_shape指定的是单个样本的形状,不需要包含批量维度(即样本总数量)。Fashion MNIST里每张图是28×28的灰度图,单样本形状为(28,28),Flatten层会将其转成1维的784个特征,对应输出形状(784)。
  • 60000是整个训练集的样本总数,但模型结构是针对单样本设计的。实际训练或推理时,Keras会自动处理批量数据:比如调用model.fit()时,它会按设定的batch_size(默认32)把数据分成若干批量,此时Flatten层的实际输入形状会是(batch_size, 28, 28),输出形状为(batch_size, 784),批量维度是动态添加的,无需在模型定义时指定。

2. 每个图像在模型中的使用阶段

  • 数据加载预处理阶段:图像从数据集文件中被读取,转换成模型可处理的张量格式(比如归一化到0-1区间),此时每个图像是独立的28×28张量。
  • 前向传播阶段:图像被打包成批量送入模型,先经Flatten层转成784维一维张量,再通过Dense层完成特征提取与分类,最终输出10类的概率分布。
  • 反向传播阶段:如果是训练过程,每个图像的预测结果会和真实标签计算损失,模型会根据损失反向更新各层权重,图像信息会参与权重调整。
  • 训练时每个图像会被重复使用多次,次数等于设置的训练轮数(epochs),每一轮都会遍历一次整个数据集。

内容的提问来源于stack exchange,提问作者mw00847

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:44:51