Python TensorFlow 值错误:形状必须是秩1,但秩为0。

4

我是按照Sentdex的教程学习神经网络的初学者。我尝试运行以下代码:

   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 = 0
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(data, 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 hm_epochs:
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                x, y = mnist.train.next_batch(batch_size)
                _, c = sess.run([optimizer, cost], feed_dict={x: x, y: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)

但它会产生以下错误:
ValueError: shape must be rank 1 but is rank 0 for 'random_normal1/:...' with shapes[]

编辑:以下是完整的Traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/common_shapes.py", line 686, in _call_cpp_shape_fn_impl
    input_tensors_as_shapes, status)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Shape must be rank 1 but is rank 0 for 'random_normal_1/RandomStandardNormal' (op: 'RandomStandardNormal') with input shapes: [].

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "a.py", line 60, in <module>
    train_neural_network(x)
  File "a.py", line 39, in train_neural_network
    prediction = neural_model(x)
  File "a.py", line 17, in neural_model
    'biases':tf.Variable(tf.random_normal(n_nodes_hl1))}
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/random_ops.py", line 76, in random_normal
    shape_tensor, dtype, seed=seed1, seed2=seed2)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gen_random_ops.py", line 420, in _random_standard_normal
    seed2=seed2, name=name)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2958, in create_op
    set_shapes_for_outputs(ret)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2209, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2159, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/common_shapes.py", line 627, in call_cpp_shape_fn
    require_shape_fn)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/common_shapes.py", line 691, in _call_cpp_shape_fn_impl
    raise ValueError(err.message)
ValueError: Shape must be rank 1 but is rank 0 for 'random_normal_1/RandomStandardNormal' (op: 'RandomStandardNormal') with input shapes: [].

我不确定我应该做什么。我想应该没有错误...

感谢帮助,如果我有任何错误,请原谅我的糟糕英语。

编辑2: 我现在添加了完整的代码。我几乎确定我的代码与sentdex视频中的代码相同。这段代码可以在那个人的电脑上运行...我错在哪里呢?


1
错误是在哪一行引发的?请发布完整的回溯。 - GPhilo
我更新了代码以获取完整的回溯信息。 - M.Utku
从回溯信息来看:"File "a.py", line 17, in neural_model"。错误出现在neural_model函数中,但你没有展示这个函数的代码... - GPhilo
谢谢您的快速回复!我已经更新了。 - M.Utku
1个回答

1

一旦你提供了完整的neural_model代码,我会根据需要更新这个答案,因为错误就在那里,但从回溯中我已经看到你有:

'biases':tf.Variable(tf.random_normal(n_nodes_hl1))

tf.random_normal需要一个形状为list的参数。

tf.random_normal(n_nodes_hl1)更改为tf.random_normal( [n_nodes_hl1] ),这样它应该可以正常工作(或者至少继续到下一个错误...)

更新:上述内容也适用于所有其他tf.random_normal的调用。

更新2:关于add()问题,你有:

l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']) + hidden_1_layer['biases'])

那个+是错误的。你可以使用tf.add(tensor1, tensor2)或者tensor1 + tensor2(TF会自动处理)。你的代码混合了这两种方法,相当于tf.add( tensor1 + tensor2 ),所以报错是因为add缺少第二个参数。

不,n_nodes_hl1 是一个数字,在Tensorflow中,标量的维度为0(因此出现了错误)。 - GPhilo
谢谢!现在它在第25行显示“add()缺少1个参数y”。 - M.Utku
谢谢!这个问题也解决了。现在它说“本地变量y在第40行被引用之前未赋值”。 - M.Utku
那是一个完全不同的问题,已经有许多解决方案了 ;) 到处搜索吧! - GPhilo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接