Tensorflow 可视化 TensorBoard 尝试~

原文地址:blog.csdn.net/silver_sail/article/details/51899659


安装Tensorflow的过程就不必说了,安装官网或者google一下,很多资源。


这次实验是在Iris数据集进行的,下载链接


代码如下:

  1. import os  
  2. import cv2  
  3. import numpy as np  
  4. import sys  
  5. import tensorflow as tf  
  6. import random  
  7. import math  
  8.   
  9. def weight_variable(shape):  
  10.     initial = tf.truncated_normal(shape, stddev=0.1)  
  11.     return tf.Variable(initial)  
  12.   
  13. def bias_variable(shape):  
  14.     initial = tf.constant(0.1, shape=shape)  
  15.     return tf.Variable(initial)  
  16.   
  17. def load_iris(path):  
  18.     #check file exist.  
  19.     if not os.path.exists(path):  
  20.         print "path is not exist"  
  21.         return  
  22.   
  23.     return_data = []  
  24.     return_label = []  
  25.     my_map = {}  
  26.     key = 0  
  27.     iris_file = open(path);  
  28.     for line in iris_file:  
  29.         #cut the \n  
  30.         line = line[:-1]  
  31.         elements = line.split(',')  
  32.   
  33.         if len(elements) == 5:  
  34.             temp = elements[:-1]  
  35.             data = [float(x) for x in temp]  
  36.             category = elements[4]  
  37.   
  38.             label = key  
  39.             if my_map.has_key(category):  
  40.                 label = my_map[category]  
  41.             else:  
  42.                 my_map[category] = key  
  43.                 key = key + 1  
  44.             label_vector = [0] * 3;  
  45.             label_vector[label] = 1;  
  46.             return_data.append(data)  
  47.             return_label.append(label_vector)  
  48.     iris_file.close()  
  49.     return return_data,return_label  
  50.       
  51. def run(train_path):  
  52.     #load data  
  53.     img,label = load_iris(train_path)  
  54.     sess = tf.InteractiveSession()  
  55.   
  56.     #first layer.  
  57.     with tf.name_scope('input'):  
  58.         x = tf.placeholder("float", shape=[None4],name='x-input')  
  59.         y_ = tf.placeholder("float", shape=[None3],name='y-input')  
  60.       
  61.     def next_batch(img,label,size):  
  62.         img_r =[]  
  63.         label_r = []  
  64.         for num in range(size):  
  65.             index = random.randint(0,len(img)-1)  
  66.             img_r.append(np.array(img[index]))  
  67.             label_r.append(np.array(label[index]))  
  68.         img_r = np.array(img_r)  
  69.         label_r = np.array(label_r)  
  70.         return {x:img_r,y_:label_r}  
  71.           
  72.     def variable_summaries(var, name):  
  73.         with tf.name_scope('summaries'):  
  74.             mean = tf.reduce_mean(var)  
  75.             tf.scalar_summary('mean/' + name, mean)  
  76.             with tf.name_scope('stddev'):  
  77.                 stddev = tf.sqrt(tf.reduce_sum(tf.square(var - mean)))  
  78.             tf.scalar_summary('sttdev/' + name, stddev)  
  79.             tf.scalar_summary('max/' + name, tf.reduce_max(var))  
  80.             tf.scalar_summary('min/' + name, tf.reduce_min(var))  
  81.             tf.histogram_summary(name, var)  
  82.   
  83.     #fully connection  
  84.     def nn_layer(input,input_dim,output_dim,layer_name,act=tf.nn.relu):  
  85.         with tf.name_scope(layer_name):  
  86.             with tf.name_scope('W'):  
  87.                 f_w_1 = weight_variable([input_dim,output_dim])  
  88.                 variable_summaries(f_w_1, layer_name + '/weights')  
  89.             with tf.name_scope('B'):  
  90.                 f_b_1 = bias_variable([output_dim])  
  91.                 variable_summaries(f_b_1, layer_name + '/bias')  
  92.             with tf.name_scope('Wx_plus_b'):  
  93.                 input_drop = tf.reshape(input,[-1,input_dim])  
  94.                 f_r_1 = tf.matmul(input_drop,f_w_1) + f_b_1  
  95.                 tf.histogram_summary(layer_name + '/pre_activations', f_r_1)  
  96.             activations = act(f_r_1, 'activation')  
  97.             tf.histogram_summary(layer_name + '/activations', activations)  
  98.             return activations  
  99.       
  100.     l1_output = nn_layer(x,4,100,'layer1')  
  101.     l2_output = nn_layer(l1_output,100,3,'layer2',act=tf.nn.softmax)  
  102.   
  103.     #  
  104.     with tf.name_scope('cross_entropy'):  
  105.         cross_entropy = -tf.reduce_sum(y_*tf.log(l2_output))  
  106.         tf.scalar_summary('cross entropy', cross_entropy)  
  107.       
  108.     with tf.name_scope('train'):  
  109.         train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)  
  110.         correct_prediction = tf.equal(tf.argmax(l2_output,1), tf.argmax(y_,1))  
  111.       
  112.     with tf.name_scope('accuracy'):  
  113.         accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))  
  114.     tf.scalar_summary('accuracy',accuracy)  
  115.       
  116.     merged = tf.merge_all_summaries()  
  117.     train_writer = tf.train.SummaryWriter('/home/ubuntu/temp/log/train',sess.graph)  
  118.     test_writer = tf.train.SummaryWriter('/home/ubuntu/temp/log/test')  
  119.     tf.initialize_all_variables().run()  
  120.       
  121.     for i in range(200000):  
  122.         if i % 100 == 0:  # Record summaries and test-set accuracy  
  123.             summary, acc = sess.run([merged, accuracy], feed_dict=next_batch(img,label,20))  
  124.             test_writer.add_summary(summary, i)  
  125.             print('Accuracy at step %s: %s' % (i, acc))  
  126.         else:  # Record train set summaries, and train  
  127.             if i % 100 == 99:  # Record execution stats  
  128.                 run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)  
  129.                 run_metadata = tf.RunMetadata()  
  130.                 summary, _ = sess.run([merged, train_step],  
  131.                               feed_dict=next_batch(img,label,20),  
  132.                               options=run_options,  
  133.                               run_metadata=run_metadata)  
  134.                 train_writer.add_run_metadata(run_metadata, 'step%d' % i)  
  135.                 train_writer.add_summary(summary, i)  
  136.                 print('Adding run metadata for', i)  
  137.             else:  # Record a summary  
  138.                 summary, _ = sess.run([merged, train_step], feed_dict=next_batch(img,label,20))  
  139.                 train_writer.add_summary(summary, i)  
  140.   
  141. if __name__ == '__main__':  
  142.     run('iris.data.set.txt')  

代码是参考tensorflow官网的例子进行实验的,官网例子如下:
  1. # Copyright 2015 The TensorFlow Authors. All Rights Reserved.  
  2. #  
  3. # Licensed under the Apache License, Version 2.0 (the 'License');  
  4. # you may not use this file except in compliance with the License.  
  5. # You may obtain a copy of the License at  
  6. #  
  7. #     http://www.apache.org/licenses/LICENSE-2.0  
  8. #  
  9. # Unless required by applicable law or agreed to in writing, software  
  10. # distributed under the License is distributed on an 'AS IS' BASIS,  
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  12. # See the License for the specific language governing permissions and  
  13. # limitations under the License.  
  14. # ==============================================================================  
  15. """A simple MNIST classifier which displays summaries in TensorBoard. 
  16.  This is an unimpressive MNIST model, but it is a good example of using 
  17. tf.name_scope to make a graph legible in the TensorBoard graph explorer, and of 
  18. naming summary tags so that they are grouped meaningfully in TensorBoard. 
  19. It demonstrates the functionality of every TensorBoard dashboard. 
  20. """  
  21. from __future__ import absolute_import  
  22. from __future__ import division  
  23. from __future__ import print_function  
  24.   
  25. import tensorflow as tf  
  26.   
  27. from tensorflow.examples.tutorials.mnist import input_data  
  28.   
  29. flags = tf.app.flags  
  30. FLAGS = flags.FLAGS  
  31. flags.DEFINE_boolean('fake_data'False'If true, uses fake data '  
  32.                      'for unit testing.')  
  33. flags.DEFINE_integer('max_steps'1000'Number of steps to run trainer.')  
  34. flags.DEFINE_float('learning_rate'0.001'Initial learning rate.')  
  35. flags.DEFINE_float('dropout'0.9'Keep probability for training dropout.')  
  36. flags.DEFINE_string('data_dir''/tmp/data''Directory for storing data')  
  37. flags.DEFINE_string('summaries_dir''/tmp/mnist_logs''Summaries directory')  
  38.   
  39.   
  40. def train():  
  41.   # Import data  
  42.   mnist = input_data.read_data_sets(FLAGS.data_dir,  
  43.                                     one_hot=True,  
  44.                                     fake_data=FLAGS.fake_data)  
  45.   
  46.   sess = tf.InteractiveSession()  
  47.   
  48.   # Create a multilayer model.  
  49.   
  50.   # Input placehoolders  
  51.   with tf.name_scope('input'):  
  52.     x = tf.placeholder(tf.float32, [None784], name='x-input')  
  53.     y_ = tf.placeholder(tf.float32, [None10], name='y-input')  
  54.   
  55.   with tf.name_scope('input_reshape'):  
  56.     image_shaped_input = tf.reshape(x, [-128281])  
  57.     tf.image_summary('input', image_shaped_input, 10)  
  58.   
  59.   # We can't initialize these variables to 0 - the network will get stuck.  
  60.   def weight_variable(shape):  
  61.     """Create a weight variable with appropriate initialization."""  
  62.     initial = tf.truncated_normal(shape, stddev=0.1)  
  63.     return tf.Variable(initial)  
  64.   
  65.   def bias_variable(shape):  
  66.     """Create a bias variable with appropriate initialization."""  
  67.     initial = tf.constant(0.1, shape=shape)  
  68.     return tf.Variable(initial)  
  69.   
  70.   def variable_summaries(var, name):  
  71.     """Attach a lot of summaries to a Tensor."""  
  72.     with tf.name_scope('summaries'):  
  73.       mean = tf.reduce_mean(var)  
  74.       tf.scalar_summary('mean/' + name, mean)  
  75.       with tf.name_scope('stddev'):  
  76.         stddev = tf.sqrt(tf.reduce_sum(tf.square(var - mean)))  
  77.       tf.scalar_summary('sttdev/' + name, stddev)  
  78.       tf.scalar_summary('max/' + name, tf.reduce_max(var))  
  79.       tf.scalar_summary('min/' + name, tf.reduce_min(var))  
  80.       tf.histogram_summary(name, var)  
  81.   
  82.   def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):  
  83.     """Reusable code for making a simple neural net layer. 
  84.     It does a matrix multiply, bias add, and then uses relu to nonlinearize. 
  85.     It also sets up name scoping so that the resultant graph is easy to read, 
  86.     and adds a number of summary ops. 
  87.     """  
  88.     # Adding a name scope ensures logical grouping of the layers in the graph.  
  89.     with tf.name_scope(layer_name):  
  90.       # This Variable will hold the state of the weights for the layer  
  91.       with tf.name_scope('weights'):  
  92.         weights = weight_variable([input_dim, output_dim])  
  93.         variable_summaries(weights, layer_name + '/weights')  
  94.       with tf.name_scope('biases'):  
  95.         biases = bias_variable([output_dim])  
  96.         variable_summaries(biases, layer_name + '/biases')  
  97.       with tf.name_scope('Wx_plus_b'):  
  98.         preactivate = tf.matmul(input_tensor, weights) + biases  
  99.         tf.histogram_summary(layer_name + '/pre_activations', preactivate)  
  100.       activations = act(preactivate, 'activation')  
  101.       tf.histogram_summary(layer_name + '/activations', activations)  
  102.       return activations  
  103.   
  104.   hidden1 = nn_layer(x, 784500'layer1')  
  105.   
  106.   with tf.name_scope('dropout'):  
  107.     keep_prob = tf.placeholder(tf.float32)  
  108.     tf.scalar_summary('dropout_keep_probability', keep_prob)  
  109.     dropped = tf.nn.dropout(hidden1, keep_prob)  
  110.   
  111.   y = nn_layer(dropped, 50010'layer2', act=tf.nn.softmax)  
  112.   
  113.   with tf.name_scope('cross_entropy'):  
  114.     diff = y_ * tf.log(y)  
  115.     with tf.name_scope('total'):  
  116.       cross_entropy = -tf.reduce_mean(diff)  
  117.     tf.scalar_summary('cross entropy', cross_entropy)  
  118.   
  119.   with tf.name_scope('train'):  
  120.     train_step = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(  
  121.         cross_entropy)  
  122.   
  123.   with tf.name_scope('accuracy'):  
  124.     with tf.name_scope('correct_prediction'):  
  125.       correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))  
  126.     with tf.name_scope('accuracy'):  
  127.       accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  128.     tf.scalar_summary('accuracy', accuracy)  
  129.   
  130.   # Merge all the summaries and write them out to /tmp/mnist_logs (by default)  
  131.   merged = tf.merge_all_summaries()  
  132.   train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train',  
  133.                                         sess.graph)  
  134.   test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test')  
  135.   tf.initialize_all_variables().run()  
  136.   
  137.   # Train the model, and also write summaries.  
  138.   # Every 10th step, measure test-set accuracy, and write test summaries  
  139.   # All other steps, run train_step on training data, & add training summaries  
  140.   
  141.   def feed_dict(train):  
  142.     """Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""  
  143.     if train or FLAGS.fake_data:  
  144.       xs, ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)  
  145.       k = FLAGS.dropout  
  146.     else:  
  147.       xs, ys = mnist.test.images, mnist.test.labels  
  148.       k = 1.0  
  149.     return {x: xs, y_: ys, keep_prob: k}  
  150.   
  151.   for i in range(FLAGS.max_steps):  
  152.     if i % 10 == 0:  # Record summaries and test-set accuracy  
  153.       summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))  
  154.       test_writer.add_summary(summary, i)  
  155.       print('Accuracy at step %s: %s' % (i, acc))  
  156.     else:  # Record train set summaries, and train  
  157.       if i % 100 == 99:  # Record execution stats  
  158.         run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)  
  159.         run_metadata = tf.RunMetadata()  
  160.         summary, _ = sess.run([merged, train_step],  
  161.                               feed_dict=feed_dict(True),  
  162.                               options=run_options,  
  163.                               run_metadata=run_metadata)  
  164.         train_writer.add_run_metadata(run_metadata, 'step%d' % i)  
  165.         train_writer.add_summary(summary, i)  
  166.         print('Adding run metadata for', i)  
  167.       else:  # Record a summary  
  168.         summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))  
  169.         train_writer.add_summary(summary, i)  
  170.   
  171.   
  172. def main(_):  
  173.   if tf.gfile.Exists(FLAGS.summaries_dir):  
  174.     tf.gfile.DeleteRecursively(FLAGS.summaries_dir)  
  175.   tf.gfile.MakeDirs(FLAGS.summaries_dir)  
  176.   train()  
  177.   
  178.   
  179. if __name__ == '__main__':  
  180.   tf.app.run()  

有了这个代码,就可以运行了。因为自己设置的目录是/home/ubuntu/temp/log,所以在tensorboard运行的时候要指定这个目录。

命令如下:

  1. python tensorboard.py --logdir=/home/ubuntu/temp/log  

之后访问一下指定地址:


如果访问没有数据,可以在命令后面加上--debug来查看详细信息,


红色标记的是tensorboard监视的目录,查看一下是否正确。


如果还是不正确。。。就只能安装官网Readme来排查了:


就是这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值