TensorFlow训练MNIST手写数字识别网络报错:无法将dict转为Tensor
解决你的MNIST手写数字识别神经网络错误
首先,直接点出你报错的核心原因:在构建网络层时,你错误地把存储权重和偏置的字典(比如H1、H2、H3)传给了tf.matmul,但这个函数需要的是经过前一层计算后的激活张量(也就是FinalH1、FinalH2、FinalH3),这就导致TensorFlow无法把字典转换成张量,抛出了类型错误。
除此之外,你的代码还有几个小细节需要修正,我来一步步帮你解决:
1. 修正网络层的计算逻辑
在neuralNetwork函数里,每一层的输入必须是前一层输出的激活张量,而不是权重字典:
- 计算
FinalH2时,要用FinalH1代替H1 - 计算
FinalH3时,要用FinalH2代替H2 - 计算
FinalOut时,要用FinalH3代替H3
2. 修正Session的初始化语法
with tf.Session as sess:少了括号,正确写法是with tf.Session() as sess:
3. 修正优化器变量名的拼写错误
你定义的优化器变量是optimizingTool,但后面调用时写成了optimizer,要保持变量名一致。
修正后的完整代码
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data", one_hot=True) numNodesH1 = 600 numNodesH2 = 500 numNodesH3 = 500 numNodesOut = 10 sizeOfBatch = 150 y = tf.placeholder("float") x = tf.placeholder("float", [None, 784]) def neuralNetwork(value): # 定义各层的权重和偏置字典 H1 = {'weights': tf.Variable(tf.random_normal([784, numNodesH1])), "biases": tf.Variable(tf.random_normal([numNodesH1]))} H2 = {'weights': tf.Variable(tf.random_normal([numNodesH1, numNodesH2])), "biases": tf.Variable(tf.random_normal([numNodesH2]))} H3 = {"weights": tf.Variable(tf.random_normal([numNodesH2, numNodesH3])), "biases": tf.Variable(tf.random_normal([numNodesH3]))} output = {"weights": tf.Variable(tf.random_normal([numNodesH3, numNodesOut])), "biases": tf.Variable(tf.random_normal([numNodesOut]))} # 修正每一层的输入:使用前一层的激活张量而非权重字典 FinalH1 = tf.add(tf.matmul(value, H1["weights"]), H1["biases"]) FinalH1 = tf.nn.relu(FinalH1) FinalH2 = tf.add(tf.matmul(FinalH1, H2["weights"]), H2["biases"]) FinalH2 = tf.nn.relu(FinalH2) FinalH3 = tf.add(tf.matmul(FinalH2, H3["weights"]), H3["biases"]) FinalH3 = tf.nn.relu(FinalH3) FinalOut = tf.matmul(FinalH3, output["weights"]) + output["biases"] return FinalOut def train(inputdata): prediction = neuralNetwork(inputdata) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) optimizingTool = tf.train.AdamOptimizer().minimize(cost) epochsNum = 10 # 修正Session初始化语法 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(epochsNum): lostEpochs = 0 for o in range(int(mnist.train.num_examples / sizeOfBatch)): ex, ey = mnist.train.next_batch(sizeOfBatch) # 修正优化器变量名 _, c = sess.run([optimizingTool, cost], feed_dict={x: ex, y: ey}) lostEpochs += c print(f"Epochs completed = {i} / {epochsNum}, epoch loss = {lostEpochs}") correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) neuralAccuracy = tf.reduce_mean(tf.cast(correct, "float")) print(f"Test Accuracy: {neuralAccuracy.eval({x: mnist.test.images, y: mnist.test.labels})}") train(x)
额外小提示
作为初学者,建议你在构建每一层后,打印张量的形状(比如print(FinalH1.get_shape())),这样能快速发现输入输出维度不匹配或者传错参数的问题,帮你更快排查错误。
内容的提问来源于stack exchange,提问作者LeoTheDev
相关产品推荐
相关产品推荐

