使用tensorflow_datasets加载MNIST时出现'list'对象无'train'属性报错
报错根因
tfds.load 传入split列表时返回的是对应数据集分片组成的列表,不存在 .train/.test 这类属性,和旧版tensorflow.examples.tutorials.mnist返回的结构化数据对象结构完全不同,直接调用.train.next_batch()自然会触发属性错误。
适配改造方案
你当前使用的是TF1兼容模式下的placeholder + feed_dict训练逻辑,不需要引入复杂的tf.data管道,只要将tfds加载的数据集转为numpy数组,复刻旧API的两个核心能力即可:
- 训练集支持随机采样小批量的
next_batch功能 - 测试集可直接获取全量图像、标签的numpy数组,用于分批次测试
关键修改点
- 对
tfds.load的返回列表做解构,分别拿到训练、测试分片的Dataset对象 - 配置
as_supervised=True直接返回(图像, 标签)元组,省去手动解析Dataset字段的步骤 - 全量加载数据到numpy数组,完成形状适配:
- 将28*28的二维图像展平为784维向量,匹配输入placeholder的维度要求
- 整数标签转one-hot编码,匹配输出占位符的维度
- 按旧版教程的规则将像素值归一化到0-1区间,避免训练精度异常
- 实现简单的随机采样函数替代旧版的
next_batch逻辑
完整可运行代码
import tensorflow_datasets as tfds import tensorflow as tf import numpy as np # 保留原有自定义层导入 from layers import conv_layer, max_pool_2x2, full_layer tf.compat.v1.disable_eager_execution() DATA_DIR = '../data/' MINIBATCH_SIZE = 50 STEPS = 5000 # 数据集加载逻辑改造 # 解构列表:第一位为训练集分片,第二位为测试集分片 ds_train, ds_test = tfds.load( name='mnist', split=['train', 'test'], data_dir=DATA_DIR, as_supervised=True, batch_size=-1 # 一次性加载全量数据,MNIST体积极小无内存压力 ) # 转换为numpy格式 train_imgs, train_labels = tfds.as_numpy(ds_train) test_imgs, test_labels = tfds.as_numpy(ds_test) # 图像形状适配 + 归一化 train_imgs = train_imgs.reshape(-1, 28*28).astype(np.float32) / 255.0 test_imgs = test_imgs.reshape(-1, 28*28).astype(np.float32) / 255.0 # 标签转one-hot编码 train_labels = np.eye(10)[train_labels] test_labels = np.eye(10)[test_labels] # 替代旧版next_batch的批量采样函数 def next_batch(batch_size): sample_idx = np.random.choice(len(train_imgs), batch_size) return train_imgs[sample_idx], train_labels[sample_idx] # 原有网络结构保持不变 x = tf.compat.v1.placeholder(tf.float32, shape=[None, 784]) y_ = tf.compat.v1.placeholder(tf.float32, shape=[None, 10]) x_image = tf.reshape(x, [-1, 28, 28, 1]) conv1 = conv_layer(x_image, shape=[5, 5, 1, 32]) conv1_pool = max_pool_2x2(conv1) conv2 = conv_layer(conv1_pool, shape=[5, 5, 32, 64]) conv2_pool = max_pool_2x2(conv2) conv2_flat = tf.reshape(conv2_pool, [-1, 7*7*64]) full_1 = tf.nn.relu(full_layer(conv2_flat, 1024)) keep_prob = tf.compat.v1.placeholder(tf.float32) full1_drop = tf.nn.dropout(full_1, rate=1-keep_prob) y_conv = full_layer(full1_drop, 10) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_)) train_step = tf.compat.v1.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.global_variables_initializer()) for i in range(STEPS): batch = next_batch(MINIBATCH_SIZE) if i % 100 == 0: train_accuracy = sess.run(accuracy, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0}) print("step {}, training accuracy {}".format(i, train_accuracy)) sess.run(train_step, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) # 全量测试集分块计算精度 X = test_imgs.reshape(10, 1000, 784) Y = test_labels.reshape(10, 1000, 10) test_accuracy = np.mean( [sess.run(accuracy, feed_dict={x: X[i], y_: Y[i], keep_prob: 1.0}) for i in range(10)]) print("test accuracy: {}".format(test_accuracy))
额外说明
- 自定义的随机采样逻辑和旧版MNIST API的
next_batch行为基本一致,不需要额外维护训练数据的迭代位置 - 如果后续需要适配更大的数据集(无法一次性加载到内存),可以去掉
batch_size=-1参数,通过迭代tf.data.Dataset的方式逐批获取数据,不需要改动网络训练的核心逻辑
内容的提问来源于stack exchange,提问作者afettouhi
相关产品推荐
相关产品推荐

