在TensorFlow

时间:2016-05-04 03:13:13

标签: python printing tensorflow

抱歉,我知道有这篇文章 How to print the value of a Tensor object in TensorFlow?

但我是初学者,我不明白帖子中的答案。

我有这段代码

batch_size = 128
num_RELU =1024
graph1 = tf.Graph()
with graph1.as_default():

  # Input data. For the training data, we use a placeholder that will be fed
  # at run time with a training minibatch.
  tf_train_dataset = tf.placeholder(tf.float32,
                                    shape=(batch_size, image_size * image_size))
  tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
  tf_valid_dataset = tf.constant(valid_dataset)
  tf_test_dataset = tf.constant(test_dataset)

  # Variables.
  weights_RELU = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_RELU]))
  biases_RELU = tf.Variable(tf.zeros([num_RELU]))
  weights_layer1 = tf.Variable(
    tf.truncated_normal([num_RELU, num_labels]))
  biases_layer1 = tf.Variable(tf.zeros([num_labels]))

  # Training computation.
  logits_RELU = tf.matmul(tf_train_dataset, weights_RELU) + biases_RELU
  RELU_vec = tf.nn.relu(logits_RELU)
  logits_layer = tf.matmul(RELU_vec, weights_layer1) + biases_layer1                  
  loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits_layer, tf_train_labels))

  # Optimizer.
  optimizer = tf.train.GradientDescentOptimizer(0.3).minimize(loss)

  # Predictions for the training, validation, and test data.
  train_prediction = tf.nn.softmax(logits_layer)
  valid_prediction = tf.nn.softmax(
    tf.matmul(tf.nn.relu((tf.matmul(tf_valid_dataset, weights_RELU) + biases_RELU)),weights_layer1)+biases_layer1)

  test_prediction =tf.nn.softmax(
    tf.matmul(tf.nn.relu((tf.matmul(tf_test_dataset, weights_RELU) + biases_RELU)),weights_layer1)+biases_layer1)

接着是

import datetime

startTime = datetime.datetime.now() 

num_steps = 301 #3001
with tf.Session(graph=graph1) as session:

  tf.initialize_all_variables().run()
  print("Initialized")
  for step in range(num_steps):
    # Pick an offset within the training data, which has been randomized.
    # Note: we could use better randomization across epochs.
    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
    # Generate a minibatch. 
    batch_data = train_dataset[offset:(offset + batch_size), :]
    batch_labels = train_labels[offset:(offset + batch_size), :]
    # Prepare a dictionary telling the session where to feed the minibatch.
    # The key of the dictionary is the placeholder node of the graph to be fed,
    # and the value is the numpy array to feed to it.
    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
    _, l, predictions = session.run(
      [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
        valid_prediction.eval(), valid_labels))
  print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))

  tf.Print(logits_RELU,[logits_RELU],message="This is logits:") #this in itself doesn't print anything

  logits_RELU.eval() #this is what i tried reading the other post

x = datetime.datetime.now() - startTime
print(x)

返回以下错误

 InvalidArgumentError                      Traceback (most recent call
 last) <ipython-input-75-b79445d934e0> in <module>()
      29   print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
      30   tf.Print(logits_RELU,[logits_RELU],message="This is logits:")
 ---> 31   logits_RELU.eval()
      32 x = datetime.datetime.now() - startTime
      33 print(x)

 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc
 in eval(self, feed_dict, session)
     463 
     464     """
 --> 465     return _eval_using_default_session(self, feed_dict, self.graph, session)
     466 
     467 

 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc
 in _eval_using_default_session(tensors, feed_dict, graph, session)   
 3095                        "the tensor's graph is different from the
 session's "    3096                        "graph.")
 -> 3097   return session.run(tensors, feed_dict)    3098     3099 

 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/client/session.pyc
 in run(self, fetches, feed_dict)
     313         `Tensor` that doesn't exist.
     314     """
 --> 315     return self._run(None, fetches, feed_dict)
     316 
     317   def partial_run(self, handle, fetches, feed_dict=None):

 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/client/session.pyc
 in _run(self, handle, fetches, feed_dict)
     509     # Run request and get response.
     510     results = self._do_run(handle, target_list, unique_fetches,
 --> 511                            feed_dict_string)
     512 
     513     # User may have fetched the same tensor multiple times, but we

 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/client/session.pyc
 in _do_run(self, handle, target_list, fetch_list, feed_dict)
     562     if handle is None:
     563       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
 --> 564                            target_list)
     565     else:
     566       return self._do_call(_prun_fn, self._session, handle, feed_dict,

 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/client/session.pyc
 in _do_call(self, fn, *args)
     584         # pylint: disable=protected-access
     585         raise errors._make_specific_exception(node_def, op, error_message,
 --> 586                                               e.code)
     587         # pylint: enable=protected-access
     588       six.reraise(e_type, e_value, e_traceback)

 InvalidArgumentError: You must feed a value for placeholder tensor
 'Placeholder' with dtype float and shape [128,784]      [[Node:
 Placeholder = Placeholder[dtype=DT_FLOAT, shape=[128,784],
 _device="/job:localhost/replica:0/task:0/cpu:0"]()]] Caused by op u'Placeholder', defined at:   File
 "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py",
 line 162, in _run_module_as_main
     "__main__", fname, loader, pkg_name)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py",
 line 72, in _run_code
     exec code in run_globals   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipykernel/__main__.py",
 line 3, in <module>
     app.launch_new_instance()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitlets/config/application.py",
 line 596, in launch_instance
     app.start()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipykernel/kernelapp.py",
 line 442, in start
     ioloop.IOLoop.instance().start()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/zmq/eventloop/ioloop.py",
 line 162, in start
     super(ZMQIOLoop, self).start()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tornado/ioloop.py",
 line 883, in start
     handler_func(fd_obj, events)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tornado/stack_context.py",
 line 275, in null_wrapper
     return fn(*args, **kwargs)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py",
 line 440, in _handle_events
     self._handle_recv()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py",
 line 472, in _handle_recv
     self._run_callback(callback, msg)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py",
 line 414, in _run_callback
     callback(*args, **kwargs)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tornado/stack_context.py",
 line 275, in null_wrapper
     return fn(*args, **kwargs)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipykernel/kernelbase.py",
 line 276, in dispatcher
     return self.dispatch_shell(stream, msg)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipykernel/kernelbase.py",
 line 228, in dispatch_shell
     handler(stream, idents, msg)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipykernel/kernelbase.py",
 line 391, in execute_request
     user_expressions, allow_stdin)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipykernel/ipkernel.py",
 line 199, in do_execute
     shell.run_cell(code, store_history=store_history, silent=silent)   File
 "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py",
 line 2723, in run_cell
     interactivity=interactivity, compiler=compiler, result=result)   File
 "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py",
 line 2825, in run_ast_nodes
     if self.run_code(code, result):   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py",
 line 2885, in run_code
     exec(code_obj, self.user_global_ns, self.user_ns)   File "<ipython-input-60-eea4738bb583>", line 9, in <module>
     shape=(batch_size, image_size * image_size))   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.py",
 line 742, in placeholder
     name=name)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py",
 line 583, in _placeholder
     name=name)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py",
 line 655, in apply_op
     op_def=op_def)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/framework/ops.py",
 line 2040, in create_op
     original_op=self._default_original_op, op_def=op_def)   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tensorflow/python/framework/ops.py",
 line 1087, in __init__
     self._traceback = _extract_stack()

1 个答案:

答案 0 :(得分:1)

当您使用tf.placeholder时,只要您尝试在会话中运行某些操作,就必须提供它们。 现在你需要占位符如下:

tf_train_dataset = tf.placeholder(tf.float32,shape=(batch_size, image_size * image_size))
tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))

当您运行会话时,您必须像在

中一样提供它们
_, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)

但您可以看到,当您拨打Tensor.eval()时就像在test_prediction.eval()中一样,您没有为占位符提供信息。 记得。只要你有占位符,你就必须在每次想要评估张量或选择时提供它们。