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

TensorFlow实现MNIST神经网络遇两类错误求助

解决TensorFlow神经网络实现中的两个关键错误

我来帮你拆解这两个错误的原因和解决办法:

第一个错误:TypeError: unhashable type: 'numpy.ndarray'

这个问题出在变量名冲突上。在train_neural_network函数里,你写了:

x, y = mnist.train.next_batch(batch_size)

这里的x和y直接覆盖了函数外部定义的TensorFlow占位符x = tf.placeholder('float',[None, 784])和y = tf.placeholder('float')。当你在feed_dict={x:x, y:y}里使用时,左边的键本应该是可哈希的Tensor占位符对象,但现在变成了右边的numpy数组(不可哈希类型),所以触发了这个错误。

解决办法:把batch数据的变量名改成别的,比如batch_x和batch_y,修改这部分代码:

for _ in range(int(mnist.train.num_examples/batch_size)):
    batch_x, batch_y = mnist.train.next_batch(batch_size)
    _, c = sess.run([optimizer, cost], feed_dict={x:batch_x, y:batch_y})

第二个错误:InvalidArgumentError: Reshape cannot infer the missing input size...

这个错误的根源是分类数设置错误。你代码里写了n_classes = 0,但MNIST数据集是10个手写数字分类(0-9),所以n_classes必须设为10。

当n_classes=0时,输出层的权重矩阵维度是[500, 0],导致输出张量是空的。后续的tf.nn.softmax_cross_entropy_with_logits在处理空张量时,内部的Reshape操作无法推断合法维度,就抛出了这个错误。

解决办法:修改n_classes的定义:

n_classes = 10

修改后的完整代码

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500
n_classes = 10  # 修正分类数
batch_size = 100

x = tf.placeholder('float',[None, 784])
y = tf.placeholder('float')

def neural_model(impuls):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])), 
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 
                    'biases':tf.Variable(tf.random_normal([n_classes]))}

    l1 = tf.add(tf.matmul(impuls, hidden_1_layer['weights']), hidden_1_layer['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']) , hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']) , hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']
    return output

def train_neural_network(x):
    prediction = neural_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 10
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                batch_x, batch_y = mnist.train.next_batch(batch_size)  # 修正变量名
                _, c = sess.run([optimizer, cost], feed_dict={x:batch_x, y:batch_y})
                epoch_loss += c
            print('Epoch: ', epoch, 'completed out of', hm_epochs, 'loss: ', epoch_loss)
        
        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1))
        ac = tf.reduce_mean(tf.cast(correct, 'float'))
        print('acc: ', ac.eval({x:mnist.test_images, y:mnist.test_labels}))

train_neural_network(x)

这样修改后,两个错误都应该能解决,你可以运行试试~

内容的提问来源于stack exchange,提问作者M.Utku

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:21:11