ValueError:无法为张量的Placeholder_4:0提供形状(128,)的值,它有形状(?),1161)

时间:2022-06-05 13:48:34

I am facing a Value Error in Tensorflow's placeholder tensor. I have declared it as [None, n_classes] so that it can accept batch of any size. Yet I am facing a ValueError that there is a mismatch with the batch size and the tensor label feed.

我在Tensorflow的占位张量中遇到一个值错误。我已经声明它为[None, n_classes],以便它可以接受任意大小的批处理。然而,我正面临一个ValueError,它与批处理大小和张量标签提要不匹配。

Following is the code:

下面是代码:

n_inputs = 5000
n_classes = 1161
features = tf.placeholder(tf.float32, [None, n_inputs])
labels = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32)

h_layer = 256

weights = {
'hidden_weights' : tf.Variable(tf.random_normal([n_inputs, h_layer])),
'out_weights' : tf.Variable(tf.random_normal([h_layer, n_classes]))
}

bias = {
'hidden_bias' : tf.Variable(tf.random_normal([h_layer])),
'out_bias' : tf.Variable(tf.random_normal([n_classes]))
}

hidden_output1 = tf.add(tf.matmul(features, weights['hidden_weights']),bias['hidden_bias'])
hidden_relu1 = tf.nn.relu(hidden_output1)
hidden_out = tf.nn.dropout(hidden_relu1, keep_prob)

hidden_output2 = tf.add(tf.matmul(hidden_out, weights['out_weights']),bias['out_bias'])
logits = tf.nn.relu(hidden_output2)
logits = tf.nn.dropout(logits, keep_prob)
learn_rate = 0.001


cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = labels))

optimizer = tf.train.GradientDescentOptimizer(learning_rate = learn_rate).minimize(cost)

correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(labels,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

batchSize =  128 

epochs = 1000
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init) 
    total_batches = batches(batchSize, train_features, train_labels)

    for epoch in range(epochs): 
        for batch_features, batch_labels in total_batches: 
            train_data = {features: batch_features, labels : batch_labels, keep_prob : 0.7}
            sess.run(optimizer, feed_dict = train_data)
        # Print status for every 100 epochs
        if epoch % 1000 == 0:
            valid_accuracy = sess.run(
                accuracy,
                feed_dict={
                    features: val_features,
                    labels: val_labels,
                    keep_prob : 0.7})
            print('Epoch {:<3} - Validation Accuracy: {}'.format(
                epoch,
                valid_accuracy))
    Accuracy = sess.run(accuracy, feed_dict={features : test_features, labels :test_labels, keep_prob : 0.7})

    print('Trained Model Saved.')
print("Accuracy value is {}".format(Accuracy))

Adding the stack trace of the code:

添加代码的堆栈跟踪:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-6e6a72faba19> in <module>()
     45         for batch_features, batch_labels in total_batches:
     46             train_data = {features: batch_features, labels : batch_labels, keep_prob : 0.7}
---> 47             sess.run(optimizer, feed_dict = train_data)
     48         # Print status for every 100 epochs
     49         if epoch % 1000 == 0:

C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    765     try:
    766       result = self._run(None, fetches, feed_dict, options_ptr,
--> 767                          run_metadata_ptr)
    768       if run_metadata:
    769         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    942                 'Cannot feed value of shape %r for Tensor %r, '
    943                 'which has shape %r'
--> 944                 % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
    945           if not self.graph.is_feedable(subfeed_t):
    946             raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (128,) for Tensor 'Placeholder_4:0', which has shape '(?, 1161)'

Am I missing anything in the syntax ?

我在语法中漏掉了什么吗?

**EDIT **

* *编辑* *

After changing the

后改变了

labels = tf.placeholder(tf.int32, [None]) and 
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = tf.one_hot(labels, num_classes)))

stack trace is :

堆栈跟踪:

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1021     try:
-> 1022       return fn(*args)
   1023     except errors.OpError as e:

C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1003                                  feed_dict, fetch_list, target_list,
-> 1004                                  status, run_metadata)
   1005 

C:\Anaconda\envs\tensorflow\lib\contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

InvalidArgumentError: Expected dimension in the range [-1, 1), but got 1
     [[Node: ArgMax_1 = ArgMax[T=DT_INT32, Tidx=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_4_0, ArgMax_1/dimension)]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-12-8e96f1dbdfec> in <module>()
     53                     features: val_features,
     54                     labels: val_labels,
---> 55                     keep_prob : 0.7})
     56             print('Epoch {:<3} - Validation Accuracy: {}'.format(
     57                 epoch,

C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    765     try:
    766       result = self._run(None, fetches, feed_dict, options_ptr,
--> 767                          run_metadata_ptr)
    768       if run_metadata:
    769         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    963     if final_fetches or final_targets:
    964       results = self._do_run(handle, final_targets, final_fetches,
--> 965                              feed_dict_string, options, run_metadata)
    966     else:
    967       results = []

C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1013     if handle is None:
   1014       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1015                            target_list, options, run_metadata)
   1016     else:
   1017       return self._do_call(_prun_fn, self._session, handle, feed_dict,

C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1033         except KeyError:
   1034           pass
-> 1035       raise type(e)(node_def, op, message)
   1036 
   1037   def _extend_graph(self):

InvalidArgumentError: Expected dimension in the range [-1, 1), but got 1
     [[Node: ArgMax_1 = ArgMax[T=DT_INT32, Tidx=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_4_0, ArgMax_1/dimension)]]

Caused by op 'ArgMax_1', defined at:
  File "C:\Anaconda\envs\tensorflow\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Anaconda\envs\tensorflow\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\tornado\ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-12-8e96f1dbdfec>", line 33, in <module>
    correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(labels,1))
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\math_ops.py", line 173, in argmax
    return gen_math_ops.arg_max(input, axis, name)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 168, in arg_max
    name=name)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 763, in apply_op
    op_def=op_def)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 2327, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 1226, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Expected dimension in the range [-1, 1), but got 1
     [[Node: ArgMax_1 = ArgMax[T=DT_INT32, Tidx=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_4_0, ArgMax_1/dimension)]]

1 个解决方案

#1


1  

As the error says, you are feeding the wrong size to the tensor: labels. labels expects the input to be [batch_size, num_classes] but you are feeding it [batch_size]. Change to labels = tf.placeholder(tf.int32, [None]) and use tf.one_hot(labels, num_classes) when you pass it to the tf.nn.softmax_cross_entropy_with_logits() function.

正如错误所说,您给张量提供了错误的大小:标签。标签期望输入是[batch_size, num_classes],但是您正在输入它[batch_size]。更改为label = tf.placeholder(tf.int32, [None])并使用tf。当您将它传递给tf.nn.softmax_cross_entropy_with_logits()函数时,one_hot(标签、num_classes)。

#1


1  

As the error says, you are feeding the wrong size to the tensor: labels. labels expects the input to be [batch_size, num_classes] but you are feeding it [batch_size]. Change to labels = tf.placeholder(tf.int32, [None]) and use tf.one_hot(labels, num_classes) when you pass it to the tf.nn.softmax_cross_entropy_with_logits() function.

正如错误所说,您给张量提供了错误的大小:标签。标签期望输入是[batch_size, num_classes],但是您正在输入它[batch_size]。更改为label = tf.placeholder(tf.int32, [None])并使用tf。当您将它传递给tf.nn.softmax_cross_entropy_with_logits()函数时,one_hot(标签、num_classes)。