{"action":"created","issue":{"url":"https://api.github.com/repos/tensorflow/tensorflow/issues/6322","repository_url":"https://api.github.com/repos/tensorflow/tensorflow","labels_url":"https://api.github.com/repos/tensorflow/tensorflow/issues/6322/labels{/name}","comments_url":"https://api.github.com/repos/tensorflow/tensorflow/issues/6322/comments","events_url":"https://api.github.com/repos/tensorflow/tensorflow/issues/6322/events","html_url":"https://github.com/tensorflow/tensorflow/issues/6322","id":195671799,"number":6322,"title":"No real code example for using the tensorboard embedding tab","user":{"login":"danielgordon10","id":7245472,"avatar_url":"https://avatars.githubusercontent.com/u/7245472?v=3","gravatar_id":"","url":"https://api.github.com/users/danielgordon10","html_url":"https://github.com/danielgordon10","followers_url":"https://api.github.com/users/danielgordon10/followers","following_url":"https://api.github.com/users/danielgordon10/following{/other_user}","gists_url":"https://api.github.com/users/danielgordon10/gists{/gist_id}","starred_url":"https://api.github.com/users/danielgordon10/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/danielgordon10/subscriptions","organizations_url":"https://api.github.com/users/danielgordon10/orgs","repos_url":"https://api.github.com/users/danielgordon10/repos","events_url":"https://api.github.com/users/danielgordon10/events{/privacy}","received_events_url":"https://api.github.com/users/danielgordon10/received_events","type":"User","site_admin":false},"labels":[{"id":404586594,"url":"https://api.github.com/repos/tensorflow/tensorflow/labels/awaiting%20googler","name":"awaiting googler","color":"b60205","default":false},{"id":283394350,"url":"https://api.github.com/repos/tensorflow/tensorflow/labels/enhancement","name":"enhancement","color":"84b6eb","default":true},{"id":284285184,"url":"https://api.github.com/repos/tensorflow/tensorflow/labels/tensorboard","name":"tensorboard","color":"5319e7","default":false}],"state":"open","locked":false,"assignee":{"login":"danmane","id":1400023,"avatar_url":"https://avatars.githubusercontent.com/u/1400023?v=3","gravatar_id":"","url":"https://api.github.com/users/danmane","html_url":"https://github.com/danmane","followers_url":"https://api.github.com/users/danmane/followers","following_url":"https://api.github.com/users/danmane/following{/other_user}","gists_url":"https://api.github.com/users/danmane/gists{/gist_id}","starred_url":"https://api.github.com/users/danmane/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/danmane/subscriptions","organizations_url":"https://api.github.com/users/danmane/orgs","repos_url":"https://api.github.com/users/danmane/repos","events_url":"https://api.github.com/users/danmane/events{/privacy}","received_events_url":"https://api.github.com/users/danmane/received_events","type":"User","site_admin":false},"assignees":[{"login":"danmane","id":1400023,"avatar_url":"https://avatars.githubusercontent.com/u/1400023?v=3","gravatar_id":"","url":"https://api.github.com/users/danmane","html_url":"https://github.com/danmane","followers_url":"https://api.github.com/users/danmane/followers","following_url":"https://api.github.com/users/danmane/following{/other_user}","gists_url":"https://api.github.com/users/danmane/gists{/gist_id}","starred_url":"https://api.github.com/users/danmane/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/danmane/subscriptions","organizations_url":"https://api.github.com/users/danmane/orgs","repos_url":"https://api.github.com/users/danmane/repos","events_url":"https://api.github.com/users/danmane/events{/privacy}","received_events_url":"https://api.github.com/users/danmane/received_events","type":"User","site_admin":false}],"milestone":null,"comments":3,"created_at":"2016-12-14T23:07:40Z","updated_at":"2016-12-16T00:16:08Z","closed_at":null,"body":"I spent a long time yesterday trying to understand how to get something to show up in the embedding tab on Tensorboard. It is not very well documented, and there are no code examples except for the tiny, incomplete snippets in the tutorial. I was finally able to get something working, but I think it would be helpful for future users to have a real code tutorial. I could pretty easily write one for the MNIST example since I already have my own working. Is that something that people will want?"},"comment":{"url":"https://api.github.com/repos/tensorflow/tensorflow/issues/comments/267483232","html_url":"https://github.com/tensorflow/tensorflow/issues/6322#issuecomment-267483232","issue_url":"https://api.github.com/repos/tensorflow/tensorflow/issues/6322","id":267483232,"user":{"login":"danielgordon10","id":7245472,"avatar_url":"https://avatars.githubusercontent.com/u/7245472?v=3","gravatar_id":"","url":"https://api.github.com/users/danielgordon10","html_url":"https://github.com/danielgordon10","followers_url":"https://api.github.com/users/danielgordon10/followers","following_url":"https://api.github.com/users/danielgordon10/following{/other_user}","gists_url":"https://api.github.com/users/danielgordon10/gists{/gist_id}","starred_url":"https://api.github.com/users/danielgordon10/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/danielgordon10/subscriptions","organizations_url":"https://api.github.com/users/danielgordon10/orgs","repos_url":"https://api.github.com/users/danielgordon10/repos","events_url":"https://api.github.com/users/danielgordon10/events{/privacy}","received_events_url":"https://api.github.com/users/danielgordon10/received_events","type":"User","site_admin":false},"created_at":"2016-12-16T00:16:08Z","updated_at":"2016-12-16T00:16:08Z","body":"Sure. I started with the fully_connected_feed.py file and added in the necessary stuff. It seems to work for me. I tried to follow the Google style as best as I could. I even used comments! It requires Numpy and Scipy, but that isn't too much to ask.\r\n\r\n```python\r\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n#     http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#\r\n# @author: Daniel Gordon <xkcd@cs.washington.edu>\r\n#\r\n# ==============================================================================\r\n\r\n\"\"\"Trains and Evaluates the MNIST network using a feed dictionary.\"\"\"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\n# pylint: disable=missing-docstring\r\nimport argparse\r\nimport os.path\r\nimport sys\r\nimport time\r\n\r\nfrom six.moves import xrange  # pylint: disable=redefined-builtin\r\nimport tensorflow as tf\r\n\r\nfrom tensorflow.contrib.tensorboard.plugins import projector\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nfrom tensorflow.examples.tutorials.mnist import mnist\r\n\r\nimport numpy as np\r\nimport scipy.misc\r\n\r\n\r\n# Basic model parameters as external flags.\r\nFLAGS = None\r\n\r\n\r\ndef placeholder_inputs(batch_size):\r\n  \"\"\"Generate placeholder variables to represent the input tensors.\r\n\r\n  These placeholders are used as inputs by the rest of the model building\r\n  code and will be fed from the downloaded data in the .run() loop, below.\r\n\r\n  Args:\r\n    batch_size: The batch size will be baked into both placeholders.\r\n\r\n  Returns:\r\n    images_placeholder: Images placeholder.\r\n    labels_placeholder: Labels placeholder.\r\n  \"\"\"\r\n  # Note that the shapes of the placeholders match the shapes of the full\r\n  # image and label tensors, except the first dimension is now batch_size\r\n  # rather than the full size of the train or test data sets.\r\n  images_placeholder = tf.placeholder(tf.float32, shape=(batch_size,\r\n                                                         mnist.IMAGE_PIXELS))\r\n  labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size))\r\n  return images_placeholder, labels_placeholder\r\n\r\n\r\ndef fill_feed_dict(data_set, images_pl, labels_pl):\r\n  \"\"\"Fills the feed_dict for training the given step.\r\n\r\n  A feed_dict takes the form of:\r\n  feed_dict = {\r\n      <placeholder>: <tensor of values to be passed for placeholder>,\r\n      ....\r\n  }\r\n\r\n  Args:\r\n    data_set: The set of images and labels, from input_data.read_data_sets()\r\n    images_pl: The images placeholder, from placeholder_inputs().\r\n    labels_pl: The labels placeholder, from placeholder_inputs().\r\n\r\n  Returns:\r\n    feed_dict: The feed dictionary mapping from placeholders to values.\r\n  \"\"\"\r\n  # Create the feed_dict for the placeholders filled with the next\r\n  # `batch size` examples.\r\n  images_feed, labels_feed = data_set.next_batch(FLAGS.batch_size,\r\n                                                 FLAGS.fake_data)\r\n  feed_dict = {\r\n      images_pl: images_feed,\r\n      labels_pl: labels_feed,\r\n  }\r\n  return feed_dict\r\n\r\n\r\ndef do_eval(sess,\r\n            eval_correct,\r\n            images_placeholder,\r\n            labels_placeholder,\r\n            data_set,\r\n            return_results=False):\r\n  \"\"\"Runs one evaluation against the full epoch of data.\r\n\r\n  Args:\r\n    sess: The session in which the model has been trained.\r\n    eval_correct: The Tensor that returns the number of correct predictions.\r\n    images_placeholder: The images placeholder.\r\n    labels_placeholder: The labels placeholder.\r\n    data_set: The set of images and labels to evaluate, from\r\n      input_data.read_data_sets().\r\n    return_results: True if the results should be returned for the embedding.\r\n\r\n  Returns:\r\n    all_images: A list of batches of images.\r\n    all_labels: A list of batches of labels.\r\n    all_hidden1_outputs: A list of batches of embeddings from the first hidden\r\n      layer.\r\n    all_hidden2_outputs: A list of batches of embeddings from the second hidden\r\n      layer.\r\n  \"\"\"\r\n  # And run one epoch of eval.\r\n  true_count = 0  # Counts the number of correct predictions.\r\n  steps_per_epoch = data_set.num_examples // FLAGS.batch_size\r\n  num_examples = steps_per_epoch * FLAGS.batch_size\r\n  if return_results:\r\n    all_images = []\r\n    all_labels = []\r\n    all_hidden1_outputs = []\r\n    all_hidden2_outputs = []\r\n    # Get the outputs before the ReLU.\r\n    hidden1_outputs = tf.get_default_graph().get_tensor_by_name('hidden1/add:0')\r\n    hidden2_outputs = tf.get_default_graph().get_tensor_by_name('hidden2/add:0')\r\n  for step in xrange(steps_per_epoch):\r\n    feed_dict = fill_feed_dict(data_set,\r\n                               images_placeholder,\r\n                               labels_placeholder)\r\n    if return_results:\r\n      all_images.append(feed_dict[images_placeholder])\r\n      all_labels.append(feed_dict[labels_placeholder])\r\n      curr_count, hidden1_output, hidden2_output = sess.run(\r\n              [eval_correct, hidden1_outputs, hidden2_outputs],\r\n              feed_dict=feed_dict)\r\n      true_count += curr_count\r\n      all_hidden1_outputs.append(hidden1_output)\r\n      all_hidden2_outputs.append(hidden2_output)\r\n    else:\r\n      true_count += sess.run(eval_correct, feed_dict=feed_dict)\r\n  precision = float(true_count) / num_examples\r\n  print('  Num examples: %d  Num correct: %d  Precision @ 1: %0.04f' %\r\n        (num_examples, true_count, precision))\r\n  if return_results:\r\n    return (all_images, all_labels, all_hidden1_outputs, all_hidden2_outputs)\r\n\r\n\r\ndef images_to_sprite(data):\r\n    \"\"\"Creates the sprite image along with any necessary padding\r\n\r\n    Args:\r\n      data: NxHxW[x3] tensor containing the images.\r\n\r\n    Returns:\r\n      data: Properly shaped HxWx3 image with any necessary padding.\r\n    \"\"\"\r\n    if len(data.shape) == 3:\r\n        data = np.tile(data[...,np.newaxis], (1,1,1,3))\r\n    data = data.astype(np.float32)\r\n    min = np.min(data.reshape((data.shape[0], -1)), axis=1)\r\n    data = (data.transpose(1,2,3,0) - min).transpose(3,0,1,2)\r\n    max = np.max(data.reshape((data.shape[0], -1)), axis=1)\r\n    data = (data.transpose(1,2,3,0) / max).transpose(3,0,1,2)\r\n    # Inverting the colors seems to look better for MNIST\r\n    data = 1 - data\r\n\r\n    n = int(np.ceil(np.sqrt(data.shape[0])))\r\n    padding = ((0, n ** 2 - data.shape[0]), (0, 0),\r\n            (0, 0)) + ((0, 0),) * (data.ndim - 3)\r\n    data = np.pad(data, padding, mode='constant',\r\n            constant_values=0)\r\n    # Tile the individual thumbnails into an image.\r\n    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3)\r\n            + tuple(range(4, data.ndim + 1)))\r\n    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])\r\n    data = (data * 255).astype(np.uint8)\r\n    return data\r\n\r\ndef run_training():\r\n  \"\"\"Train MNIST for a number of steps.\"\"\"\r\n  # Get the sets of images and labels for training, validation, and\r\n  # test on MNIST.\r\n  data_sets = input_data.read_data_sets(FLAGS.input_data_dir, FLAGS.fake_data)\r\n\r\n  # Tell TensorFlow that the model will be built into the default Graph.\r\n  with tf.Graph().as_default():\r\n    # Generate placeholders for the images and labels.\r\n    images_placeholder, labels_placeholder = placeholder_inputs(\r\n        FLAGS.batch_size)\r\n\r\n    # Build a Graph that computes predictions from the inference model.\r\n    logits = mnist.inference(images_placeholder,\r\n                             FLAGS.hidden1,\r\n                             FLAGS.hidden2)\r\n\r\n    # Add to the Graph the Ops for loss calculation.\r\n    loss = mnist.loss(logits, labels_placeholder)\r\n\r\n    # Add to the Graph the Ops that calculate and apply gradients.\r\n    train_op = mnist.training(loss, FLAGS.learning_rate)\r\n\r\n    # Add the Op to compare the logits to the labels during evaluation.\r\n    eval_correct = mnist.evaluation(logits, labels_placeholder)\r\n\r\n    # Build the summary Tensor based on the TF collection of Summaries.\r\n    summary = tf.summary.merge_all()\r\n\r\n    # Add the variable initializer Op.\r\n    init = tf.global_variables_initializer()\r\n\r\n    # Create a saver for writing training checkpoints.\r\n    saver = tf.train.Saver()\r\n\r\n    # Create a session for running Ops on the Graph.\r\n    sess = tf.Session()\r\n\r\n    # Instantiate a SummaryWriter to output summaries and the Graph.\r\n    summary_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)\r\n\r\n    # And then after everything is built:\r\n\r\n    # Run the Op to initialize the variables.\r\n    sess.run(init)\r\n\r\n    # Start the training loop.\r\n    for step in xrange(FLAGS.max_steps):\r\n      start_time = time.time()\r\n\r\n      # Fill a feed dictionary with the actual set of images and labels\r\n      # for this particular training step.\r\n      feed_dict = fill_feed_dict(data_sets.train,\r\n                                 images_placeholder,\r\n                                 labels_placeholder)\r\n\r\n      # Run one step of the model.  The return values are the activations\r\n      # from the `train_op` (which is discarded) and the `loss` Op.  To\r\n      # inspect the values of your Ops or variables, you may include them\r\n      # in the list passed to sess.run() and the value tensors will be\r\n      # returned in the tuple from the call.\r\n      _, loss_value = sess.run([train_op, loss],\r\n                               feed_dict=feed_dict)\r\n\r\n      duration = time.time() - start_time\r\n\r\n      # Write the summaries and print an overview fairly often.\r\n      if step % 100 == 0:\r\n        # Print status to stdout.\r\n        print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value, duration))\r\n        # Update the events file.\r\n        summary_str = sess.run(summary, feed_dict=feed_dict)\r\n        summary_writer.add_summary(summary_str, step)\r\n        summary_writer.flush()\r\n\r\n      # Save a checkpoint and evaluate the model periodically.\r\n      if (step + 1) % 1000 == 0 or (step + 1) == FLAGS.max_steps:\r\n        checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt')\r\n        saver.save(sess, checkpoint_file, global_step=step)\r\n        # Evaluate against the training set.\r\n        print('Training Data Eval:')\r\n        do_eval(sess,\r\n                eval_correct,\r\n                images_placeholder,\r\n                labels_placeholder,\r\n                data_sets.train)\r\n        # Evaluate against the validation set.\r\n        print('Validation Data Eval:')\r\n        do_eval(sess,\r\n                eval_correct,\r\n                images_placeholder,\r\n                labels_placeholder,\r\n                data_sets.validation)\r\n        # Evaluate against the test set.\r\n        print('Test Data Eval:')\r\n        do_eval(sess,\r\n                eval_correct,\r\n                images_placeholder,\r\n                labels_placeholder,\r\n                data_sets.test)\r\n\r\n    # Compute embeddings and save them.\r\n    thumbnail_size = int(np.sqrt(mnist.IMAGE_PIXELS))\r\n    for data_set, name in [\r\n            (data_sets.train, 'train'),\r\n            (data_sets.validation, 'validation'),\r\n            (data_sets.test, 'test')]:\r\n      output_path = os.path.join(FLAGS.log_dir, 'embed', name)\r\n      print('Computing %s Embedding' % name)\r\n      (all_images, all_labels, hidden1_vectors, hidden2_vectors) = do_eval(\r\n              sess,\r\n              eval_correct,\r\n              images_placeholder,\r\n              labels_placeholder,\r\n              data_set,\r\n              True)\r\n      embed_tensors = []\r\n      summary_writer = tf.summary.FileWriter(output_path, sess.graph)\r\n      config = projector.ProjectorConfig()\r\n      for layer, embed_vectors in enumerate([hidden1_vectors, hidden2_vectors]):\r\n        embed_tensor = tf.Variable(\r\n                np.array(embed_vectors).reshape(\r\n                    len(embed_vectors) * embed_vectors[0].shape[0], -1),\r\n                name=('%s_layer_%s' % (name, layer)))\r\n        embed_tensors.append(embed_tensor)\r\n        sess.run(embed_tensor.initializer)\r\n        embedding = config.embeddings.add()\r\n        embedding.tensor_name = embed_tensor.name\r\n        embedding.metadata_path = os.path.join(output_path, 'labels.tsv')\r\n        embedding.sprite.image_path = os.path.join(output_path, 'sprite.png')\r\n        embedding.sprite.single_image_dim.extend(\r\n                [thumbnail_size, thumbnail_size])\r\n        projector.visualize_embeddings(summary_writer, config)\r\n      result = sess.run(embed_tensors)\r\n      saver = tf.train.Saver(embed_tensors)\r\n      saver.save(sess, os.path.join(output_path, 'model.ckpt'), layer)\r\n\r\n      # Make sprite and labels.\r\n      images = np.array(all_images).reshape(\r\n              -1, thumbnail_size, thumbnail_size).astype(np.float32)\r\n      sprite = images_to_sprite(images)\r\n      scipy.misc.imsave(os.path.join(output_path, 'sprite.png'), sprite)\r\n      all_labels = np.array(all_labels).flatten()\r\n      metadata_file = open(os.path.join(output_path, 'labels.tsv'), 'w')\r\n      metadata_file.write('Name\\tClass\\n')\r\n      for ll in xrange(len(all_labels)):\r\n        metadata_file.write('%06d\\t%d\\n' % (ll, all_labels[ll]))\r\n      metadata_file.close()\r\n\r\ndef main(_):\r\n  if tf.gfile.Exists(FLAGS.log_dir):\r\n    tf.gfile.DeleteRecursively(FLAGS.log_dir)\r\n  tf.gfile.MakeDirs(FLAGS.log_dir)\r\n  run_training()\r\n\r\n\r\nif __name__ == '__main__':\r\n  parser = argparse.ArgumentParser()\r\n  parser.add_argument(\r\n      '--learning_rate',\r\n      type=float,\r\n      default=0.01,\r\n      help='Initial learning rate.'\r\n  )\r\n  parser.add_argument(\r\n      '--max_steps',\r\n      type=int,\r\n      default=2000,\r\n      help='Number of steps to run trainer.'\r\n  )\r\n  parser.add_argument(\r\n      '--hidden1',\r\n      type=int,\r\n      default=128,\r\n      help='Number of units in hidden layer 1.'\r\n  )\r\n  parser.add_argument(\r\n      '--hidden2',\r\n      type=int,\r\n      default=32,\r\n      help='Number of units in hidden layer 2.'\r\n  )\r\n  parser.add_argument(\r\n      '--batch_size',\r\n      type=int,\r\n      default=100,\r\n      help='Batch size.  Must divide evenly into the dataset sizes.'\r\n  )\r\n  parser.add_argument(\r\n      '--input_data_dir',\r\n      type=str,\r\n      default='/tmp/tensorflow/mnist/input_data',\r\n      help='Directory to put the input data.'\r\n  )\r\n  parser.add_argument(\r\n      '--log_dir',\r\n      type=str,\r\n      default='/tmp/tensorflow/mnist/logs/fully_connected_feed',\r\n      help='Directory to put the log data.'\r\n  )\r\n  parser.add_argument(\r\n      '--fake_data',\r\n      default=False,\r\n      help='If true, uses fake data for unit testing.',\r\n      action='store_true'\r\n  )\r\n\r\n  FLAGS, unparsed = parser.parse_known_args()\r\n  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\r\n```"}}
{"actor":{"display_login":"danielgordon10"}}