gpt4 book ai didi

python - Tensorflow InvalidArgumentError(请参阅上面的回溯): Minimum tensor rank: 2 but got: 1

转载 作者:行者123 更新时间:2023-11-30 22:44:47 25 4
gpt4 key购买 nike

我是 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))。为什么我会遇到这个问题以及如何修复它?

最佳答案

引用自TensorFlow官方文档 tf.argmax ,

axis: A Tensor. Must be one of the following types: int32, int64. int32, 0 <= axis < rank(input). Describes which axis of the input Tensor to reduce across. For vectors, use axis = 0.

您收到此错误是因为 argmax() 之一有一个input排名 <=1 。既然你路过axis=1 ,您需要传递秩 > 1 的张量才能获得有效的输出。

<小时/>

仔细看看你的代码,这似乎是因为 tf.argmax(y, 1) 。尝试通过0None而不是1 .

关于python - Tensorflow InvalidArgumentError(请参阅上面的回溯): Minimum tensor rank: 2 but got: 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41413582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com