繁体   English   中英

Tensorflow InvalidArgumentError(请参阅上面的回溯):最小张量等级:2但得到:1

[英]Tensorflow InvalidArgumentError (see above for traceback): Minimum tensor rank: 2 but got: 1

我是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)) 为什么会得到这个,如何解决?

引用tf.argmax上的官方TensorFlow文档,

轴:张量。 必须是以下类型之一:int32,int64。 int32,0 <=轴<rank(输入)。 描述减少输入张量的哪条轴。 对于矢量,请使用axis = 0。

您正在收到此错误,因为argmax()input的秩为<=1 由于传递的是axis=1 ,因此需要传递等级大于1的张量才能获得有效的输出。


仔细查看您的代码,这似乎是由于tf.argmax(y, 1) 尝试传递0None而不是1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM