我是TensorFlow的新手,我正在尝试编写一种算法来对CIFAR-10数据集中的图像进行分类。我收到了这个错误:
InvalidArgumentError (see above for traceback): Minimum tensor rank: 2 but got: 1
这是我的代码:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import cPickle
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500
n_classes = 10
batch_size = 100
image_size = 32*32*3 # because 3 channels
x = tf.placeholder('float', shape=(None, image_size))
y = tf.placeholder(tf.int64)
with open('test_batch','rb') as f:
test_data = cPickle.load(f)
print test_data
def neural_network_model(data):
hidden_1_layer = {'weights':tf.Variable(tf.random_normal([image_size, 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]))}
# input_data * weights + biases
l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases'])
# activation function
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_network_model(x)
cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(prediction, tf.squeeze(y)))
#learning rate = 0.001
optimizer = tf.train.AdamOptimizer().minimize(cost)
hm_epochs = 10
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for epoch in range(hm_epochs):
epoch_loss = 0
for i in range(5):
with open('data_batch_'+str(i+1),'rb') as f:
train_data = cPickle.load(f)
_, c = sess.run([optimizer, cost], feed_dict={x:train_data['data'],y:train_data['labels']})
epoch_loss += c
print 'Epoch ' + str(epoch) + ' completed out of ' + str(hm_epochs) + ' loss: ' + str(epoch_loss)
correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))//THIS IS THE LINE WHERE THE ERROR OCCURS
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
with open('test_batch','rb') as f:
test_data = cPickle.load(f)
accuracy = accuracy.eval({x:test_data['data'],y:test_data['labels']})
print 'Accuracy: ' + str(accuracy)
train_neural_network(x)
这是追溯:
Traceback (most recent call last):
File "cifar_10.py", line 72, in <module>
train_neural_network(x)
File "cifar_10.py", line 69, in train_neural_network
accuracy = accuracy.eval({x:test_data['data'],y:test_data['labels']})
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 559, in eval
return _eval_using_default_session(self, feed_dict, self.graph, session)
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3761, in _eval_using_default_session
return session.run(tensors, feed_dict)
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 717, in run
run_metadata_ptr)
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 915, in _run
feed_dict_string, options, run_metadata)
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 965, in _do_run
target_list, options, run_metadata)
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 985, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: Minimum tensor rank: 2 but got: 1
[[Node: ArgMax_1 = ArgMax[T=DT_INT64, Tidx=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_1_0, ArgMax_1/dimension)]]
Caused by op u'ArgMax_1', defined at:
File "cifar_10.py", line 72, in <module>
train_neural_network(x)
File "cifar_10.py", line 65, in train_neural_network
correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/ops/gen_math_ops.py", line 166, in arg_max
name=name)
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 749, in apply_op
op_def=op_def)
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2380, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/mddrill/anaconda2/envs/python27/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1298, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): Minimum tensor rank: 2 but got: 1
[[Node: ArgMax_1 = ArgMax[T=DT_INT64, Tidx=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_1_0, ArgMax_1/dimension)]]
我已在上面标出了错误发生的位置。它就是correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
。为什么我得到这个,我该如何解决?
答案 0 :(得分:3)
引自tf.argmax
上的官方TensorFlow文档,
轴:张量。必须是以下类型之一:int32,int64。 int32,0&lt; = axis&lt;秩(输入)。描述输入Tensor的哪个轴要减少。对于矢量,使用axis = 0。
您收到此错误的原因是其中一个argmax()
的{{1}}排名为input
。由于您要传递<=1
,因此您需要传递等级为&gt;的张量。 1获得有效输出。
仔细查看您的代码,似乎这是axis=1
的结果。尝试传递tf.argmax(y, 1)
或0
而不是None
。