TensorFlow ValueError求助:Shape需为1阶但实际为0阶
Let's break down the issues in your code step by step—there are several small but critical mistakes causing the shape error and other potential failures:
Your Original Code & Error
Code
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)
Error 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: []
Fixes for All Issues
1. Direct Cause of the Shape Error
tf.random_normal() requires a rank-1 shape tensor (a list/tuple defining the output shape), but you passed a scalar integer. Fix this for all bias initializations:
# Wrong: scalar input causes rank 0 error tf.random_normal(n_nodes_hl1) # Correct: pass a list to define a 1D shape tf.random_normal([n_nodes_hl1])
2. Incorrect Number of Classes
MNIST has 10 handwritten digit classes (0-9), but you set n_classes = 0—this breaks the output layer and softmax calculation:
n_classes = 10
3. Mismatched Parameter Name
Your neural_model function accepts impuls but references data (an undefined variable). Fix the parameter name to match:
def neural_model(data): # Changed from 'impuls' to 'data' # ... rest of the function uses 'data' correctly
4. Redundant tf.add() Calls
You're using both tf.add() and the + operator together, which is unnecessary. Replace lines like:
l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']) + hidden_1_layer['biases'])
With either:
# Option 1: Use + operator l1 = tf.matmul(data, hidden_1_layer['weights']) + hidden_1_layer['biases'] # Option 2: Use tf.add() properly l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases'])
5. Missing Parentheses for tf.Session()
Your session initialization is missing parentheses, which will throw an error when starting the session:
# Wrong with tf.Session as sess: # Correct with tf.Session() as sess:
6. Iterating Over an Integer
hm_epochs = 10 is an integer, so for epoch in hm_epochs: will throw a TypeError. Use range() instead:
for epoch in range(hm_epochs):
7. Variable Name Collision
You're overwriting the placeholder variables x and y when loading batches, breaking your feed_dict. Rename the batch variables:
# Wrong: overwrites placeholders x, y = mnist.train.next_batch(batch_size) # Correct: use unique names batch_x, batch_y = mnist.train.next_batch(batch_size) # Update feed_dict accordingly _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
8. Incorrect Test Data Access
You used mnist.test_images instead of the correct mnist.test.images (the MNIST dataset uses dot notation for test data):
print('Accuracy: ', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))
Corrected Full Code
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(data): 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.matmul(data, hidden_1_layer['weights']) + hidden_1_layer['biases'] l1 = tf.nn.relu(l1) l2 = tf.matmul(l1, hidden_2_layer['weights']) + hidden_2_layer['biases'] l2 = tf.nn.relu(l2) l3 = 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+1, 'completed out of', hm_epochs, 'loss: ', epoch_loss) correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy: ', accuracy.eval({x:mnist.test.images, y:mnist.test.labels})) train_neural_network(x)
内容的提问来源于stack exchange,提问作者M.Utku

