Python使用TensorFlow处理MNIST数据集报错'dict'无train属性如何解决
错误原因
- 核心触发点:
tensorflow_datasets.load('mnist')的返回值是Python字典,结构为{'train': 训练数据集, 'test': 测试数据集},不存在名为train的对象属性,所以调用mnist.train时触发AttributeError。 - 额外兼容问题:当前代码使用的是TensorFlow 1.x的语法(
placeholder、Session等),如果运行环境是TensorFlow 2.x,默认开启的动态图模式也会导致旧API无法正常调用。 - 其余隐藏bug:代码中未定义权重
W和偏置b变量、标签占位符y的形状错误(10分类任务形状应为[None,10]而非[None,784])、梯度下降优化器的学习率参数误写为0,2(应为0.2),这些问题不修复也会导致后续运行报错。
修复方案
建议直接替换MNIST数据集加载方式为适配旧版TF逻辑的tf.keras.datasets.mnist,同时补全缺失代码、修正语法错误,修复后的完整可运行代码如下:
# 开启TF1.x兼容模式,适配旧版API import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import numpy as np # 加载MNIST数据集,做预处理 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # 归一化+展平图像为784维向量 x_train = x_train.reshape(-1, 784).astype('float32') / 255 x_test = x_test.reshape(-1, 784).astype('float32') / 255 # 标签转onehot编码 y_train = tf.keras.utils.to_categorical(y_train, 10) y_test = tf.keras.utils.to_categorical(y_test, 10) batch_size = 100 n_batch = x_train.shape[0] // batch_size # 定义占位符 x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) # 定义权重和偏置 W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) prediction = tf.nn.softmax(tf.matmul(x, W) + b) # 定义损失函数 loss = tf.reduce_mean(tf.square(y - prediction)) # 梯度下降优化,修正学习率参数为0.2 train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) init = tf.global_variables_initializer() # 计算准确率 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 训练逻辑 with tf.Session() as sess: sess.run(init) for epoch in range(21): for batch in range(n_batch): # 按批次取训练数据 batch_xs = x_train[batch*batch_size : (batch+1)*batch_size] batch_ys = y_train[batch*batch_size : (batch+1)*batch_size] sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys}) # 每个epoch结束后计算测试集准确率 acc = sess.run(accuracy, feed_dict={x: x_test, y: y_test}) print("Iter " + str(epoch) + ", Testing accuracy " + str(acc))
内容的提问来源于stack exchange,提问作者Hermi
相关产品推荐
相关产品推荐

