Skip to main content
 首页 » 编程设计

python之Negative Dimensions Error running tensorflow教程

2025年02月15日25shanyou

我刚刚完成了 TensorFlow MNIST tutorial对于初学者。我在 Python 3 上的 Jupyter(本地安装)中运行最新版本的 TensorFlow。

我的代码如下,基本上是从教程中逐字提取的:

import tensorflow as tf 
from __future__ import absolute_import 
from __future__ import division 
from __future__ import print_function 
import argparse 
import sys 
from tensorflow.examples.tutorials.mnist import input_data 
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 
x = tf.placeholder(tf.float32,[None,784]) 
W = tf.Variable(tf.zeros([784,10])) 
b = tf.Variable(tf.zeros([10])) 
y = tf.nn.softmax(tf.matmul(x,W)+b) 
y_ = tf.placeholder(tf.float32,[None,10]) 
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y) 
sess= tf.InteractiveSession() 
init = tf.global_variables_initializer() 
sess.run(init) 
train_step = tf.train.GradientDescentOptimizer(.05).minimize(cross_entropy) 
for i in range(1000): 
batch_x,batch_y = mnist.train.next_batch(100) 
sess.run(train_step,feed_dict={x:batch_x,y:batch_y}) 

我认为问题可能出在 python3.因此,我尝试在 python 2.7 版本的 tensorflow 中运行相同的代码。没有改变。

--------------------------------------------------------------------------- 
InvalidArgumentError                      Traceback (most recent call last) 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 
   1138     try: 
-> 1139       return fn(*args) 
   1140     except errors.OpError as e: 
 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata) 
   1120                                  feed_dict, fetch_list, target_list, 
-> 1121                                  status, run_metadata) 
   1122  
 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback) 
     88             try: 
---> 89                 next(self.gen) 
     90             except StopIteration: 
 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/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: Shape [-1,10] has negative dimensions 
     [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[?,10], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 
 
During handling of the above exception, another exception occurred: 
 
InvalidArgumentError                      Traceback (most recent call last) 
<ipython-input-10-89eb8cf9286c> in <module>() 
      1 for _ in range(1000): 
      2     batch_x,batch_y = mnist.train.next_batch(100) 
----> 3     sess.run(train_step,feed_dict={x:batch_x,y:batch_y}) 
 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata) 
    787     try: 
    788       result = self._run(None, fetches, feed_dict, options_ptr, 
--> 789                          run_metadata_ptr) 
    790       if run_metadata: 
    791         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) 
 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 
    995     if final_fetches or final_targets: 
    996       results = self._do_run(handle, final_targets, final_fetches, 
--> 997                              feed_dict_string, options, run_metadata) 
    998     else: 
    999       results = [] 
 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata) 
   1130     if handle is None: 
   1131       return self._do_call(_run_fn, self._session, feed_dict, fetch_list, 
-> 1132                            target_list, options, run_metadata) 
   1133     else: 
   1134       return self._do_call(_prun_fn, self._session, handle, feed_dict, 
 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 
   1150         except KeyError: 
   1151           pass 
-> 1152       raise type(e)(node_def, op, message) 
   1153  
   1154   def _extend_graph(self): 
 
InvalidArgumentError: Shape [-1,10] has negative dimensions 
     [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[?,10], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 
 
Caused by op 'Placeholder_1', defined at: 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 193, in _run_module_as_main 
    "__main__", mod_spec) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 85, in _run_code 
    exec(code, run_globals) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py", line 16, in <module> 
    app.launch_new_instance() 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance 
    app.start() 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 477, in start 
    ioloop.IOLoop.instance().start() 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 177, in start 
    super(ZMQIOLoop, self).start() 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tornado/ioloop.py", line 888, in start 
    handler_func(fd_obj, events) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper 
    return fn(*args, **kwargs) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events 
    self._handle_recv() 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv 
    self._run_callback(callback, msg) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback 
    callback(*args, **kwargs) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper 
    return fn(*args, **kwargs) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher 
    return self.dispatch_shell(stream, msg) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell 
    handler(stream, idents, msg) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 399, in execute_request 
    user_expressions, allow_stdin) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 196, in do_execute 
    res = shell.run_cell(code, store_history=store_history, silent=silent) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 533, in run_cell 
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell 
    interactivity=interactivity, compiler=compiler, result=result) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2802, in run_ast_nodes 
    if self.run_code(code, result): 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code 
    exec(code_obj, self.user_global_ns, self.user_ns) 
  File "<ipython-input-4-c355762e89a9>", line 2, in <module> 
    y_ = tf.placeholder(tf.float32,[None,10]) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 1530, in placeholder 
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1954, in _placeholder 
    name=name) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op 
    op_def=op_def) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2506, in create_op 
    original_op=self._default_original_op, op_def=op_def) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1269, in __init__ 
    self._traceback = _extract_stack() 
 
InvalidArgumentError (see above for traceback): Shape [-1,10] has negative dimensions 
     [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[?,10], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 

有人可以告诉我我做错了什么吗?我认为修复本教程中的错误会很有用。

已解决!非常愚蠢的错误。在最后一行,我写了y,当我需要写y_的时候。如果有人能向我解释为什么这个错误会产生错误消息,我会很高兴。

请您参考如下方法:

产生这个错误的原因在于你这行代码中的一个类型:

sess.run(train_step,feed_dict={x:batch_x, y:batch_y}) 

你应该这样写:

sess.run(train_step,feed_dict={x:batch_x, y_:batch_y}) 

发生的情况是,您正在尝试将一批 100 个标签提供给一个 varibale,该 varibale 旨在保存单个值。

y 是您在此处实现的模型的输出:

y = tf.nn.softmax(tf.matmul(x,W)+b) 

y_ 表示您首先为其创建占位符变量的大小为 [100,10] 的张量。对于每次训练迭代,您将加载一批 100 个示例,这些示例将被馈送到 session 中:

y_ = tf.placeholder(tf.float32,[None,10]) 
batch_x,batch_y = mnist.train.next_batch(100) 
sess.run(train_step,feed_dict={x:batch_x,y_:batch_y}) 

我猜你的困惑是因为在 session.run() 期间必须将 batch_x 分配给 x,而 batch_y 被输入 y_。这样做的原因是训练图像 (x) 来自 MNIST 数据集,正确的标签 (y_) 也是如此,而您的模型输出/预测 ( y) 由您的卷积神经网络计算。

您将一批输入图像提供给您的 session 。您的模型对它认为该图像属于哪个类别的每个图像进行预测,最后将这些预测与正确的标签进行比较。这些步骤的最后一步在您的代码的以下行中执行:

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y) 

如您所见,通过向交叉熵函数传递来自您的数据集和预测的正确标签来调用交叉熵函数,这些标签由您的模型“即时”计算。这就是为什么必须在 session 运行期间向 y_ 传递数据,而不必对 y 执行相同的操作。