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

TensorFlow 2.x加载MNIST数据集及兼容V1代码问题求助

问题解决:TensorFlow 2.x 适配 MNIST 旧示例代码

问题1:ModuleNotFoundError: No module named 'tensorflow.examples'

TensorFlow 2.x 官方已移除 tensorflow.examples.tutorials 模块,即便启用 compat.v1 兼容模式也无法调用该模块,直接放弃旧方法,改用 TensorFlow 2.x 原生数据集加载方式即可。

问题2:无法使用 mnist.next_batch(100)

next_batch 是 TensorFlow 1.x 中 input_data.read_data_sets 返回对象的专属方法,而通过 tf.keras.datasets.mnist.load_data() 加载的是 numpy 数组格式数据集,无此方法。可通过以下两种方式替代:

方法1:手动实现批次获取逻辑

import numpy as np

# 定义批次获取函数
def next_batch(x_data, y_data, batch_size):
    # 随机生成批次索引
    idx = np.random.choice(len(x_data), batch_size, replace=False)
    return x_data[idx], y_data[idx]

# 使用示例
batch_xs, batch_ys = next_batch(x_train, y_train, 100)

方法2:用 tf.data.Dataset 构建批次数据集(推荐)

这是 TensorFlow 2.x 官方推荐的数据处理方式,支持打乱、重复等优化操作:

import tensorflow as tf

# 将numpy数组转为Dataset对象
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
# 打乱数据+设置批次大小+允许重复迭代
train_dataset = train_dataset.shuffle(len(x_train)).batch(100).repeat()

# 创建迭代器获取批次数据
iterator = iter(train_dataset)
batch_xs, batch_ys = next(iterator)

额外说明

下载GitHub的tutorial文件夹、寻找tensorflow_core文件夹的操作均无必要,TensorFlow 2.x 已整合原tensorflow_core内容,无需单独处理。使用上述适配TF2的方法即可完成原示例的核心功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:05:21