TensorFlow学习笔记(7)----TensorBoard_2

本文介绍了一个使用TensorFlow实现的全连接神经网络模型来识别MNIST手写数字数据集。该模型包括多个隐藏层,并使用了Dropout技术来防止过拟合。此外,还详细展示了如何设置超参数、构建模型、进行训练以及评估模型性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前的例子更加庞大,使用全连接识别MNIST,需要命名空间更多,程序更灵活,但基本的函数换是那些。

  1. from __future__ import absolute_import  
  2. from __future__ import division  
  3. from __future__ import print_function  
  4.   
  5. import tensorflow as tf  
  6.   
  7. from tensorflow.examples.tutorials.mnist import input_data  
  8.   
  9. flags = tf.app.flags  
  10. FLAGS = flags.FLAGS  
  11. flags.DEFINE_boolean('fake_data'False'If true, uses fake data '  
  12.                      'for unit testing.')  
  13. flags.DEFINE_integer('max_steps'1000'Number of steps to run trainer.')  
  14. flags.DEFINE_float('learning_rate'0.001'Initial learning rate.')  
  15. flags.DEFINE_float('dropout'0.5'Keep probability for training dropout.')  
  16. flags.DEFINE_string('data_dir''/tmp/data''Directory for storing data')  
  17. flags.DEFINE_string('summaries_dir''/tmp/mnist_logs''Summaries directory')  
  18.   
  19. # Import data  
  20. mnist = input_data.read_data_sets(FLAGS.data_dir,one_hot=True,fake_data=FLAGS.fake_data)  
  21. sess = tf.InteractiveSession()  
  22.   
  23. # We can't initialize these variables to 0 - the network will get stuck.  
  24. def weight_variable(shape):  
  25.   """Create a weight variable with appropriate initialization."""  
  26.   initial = tf.truncated_normal(shape, stddev=0.1)  
  27.   return tf.Variable(initial)  
  28.   
  29. def bias_variable(shape):  
  30.   """Create a bias variable with appropriate initialization."""  
  31.   initial = tf.constant(0.1, shape=shape)  
  32.   return tf.Variable(initial)  
  33.   
  34. def variable_summaries(var, name):  
  35.   """Attach a lot of summaries to a Tensor."""  
  36.   with tf.name_scope('summaries'):  
  37.     mean = tf.reduce_mean(var)  
  38.     tf.scalar_summary('mean/' + name, mean)  
  39.     with tf.name_scope('stddev'):  
  40.       stddev = tf.sqrt(tf.reduce_sum(tf.square(var - mean)))  
  41.     tf.scalar_summary('sttdev/' + name, stddev)  
  42.     tf.scalar_summary('max/' + name, tf.reduce_max(var))  
  43.     tf.scalar_summary('min/' + name, tf.reduce_min(var))  
  44.     tf.histogram_summary(name, var)  
  45.   
  46. def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):  
  47.   with tf.name_scope(layer_name):  
  48.     # This Variable will hold the state of the weights for the layer  
  49.     with tf.name_scope('weights'):  
  50.       weights = weight_variable([input_dim, output_dim])  
  51.       variable_summaries(weights, layer_name + '/weights')  
  52.     with tf.name_scope('biases'):  
  53.       biases = bias_variable([output_dim])  
  54.       variable_summaries(biases, layer_name + '/biases')  
  55.     with tf.name_scope('Wx_plus_b'):  
  56.       preactivate = tf.matmul(input_tensor, weights) + biases  
  57.       tf.histogram_summary(layer_name + '/pre_activations', preactivate)  
  58.     activations = act(preactivate, 'activation')  
  59.     tf.histogram_summary(layer_name + '/activations', activations)  
  60.     return activations  
  61.   
  62. # Input placehoolders  
  63. with tf.name_scope('input'):  
  64.   x = tf.placeholder(tf.float32, [None784], name='x-input')  
  65.   y_ = tf.placeholder(tf.float32, [None10], name='y-input')  
  66.   
  67. keep_prob = tf.placeholder(tf.float32)  
  68.   
  69. def feed_dict(train):  
  70.   """Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""  
  71.   if train or FLAGS.fake_data:  
  72.     xs, ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)  
  73.     k = FLAGS.dropout  
  74.   else:  
  75.     xs, ys = mnist.test.images, mnist.test.labels  
  76.     k = 1.0  
  77.   return {x: xs, y_: ys, keep_prob: k}  
  78.   
  79. def train():  
  80.   
  81.   with tf.name_scope('input_reshape'):  
  82.     image_shaped_input = tf.reshape(x, [-128281])  
  83.     tf.image_summary('input', image_shaped_input, 10)  
  84.   
  85.   hidden1 = nn_layer(x, 784500'layer1')  
  86.   
  87.   
  88.   with tf.name_scope('dropout1'):  
  89.     tf.scalar_summary('dropout_keep_probability1', keep_prob)  
  90.     dropped1 = tf.nn.dropout(hidden1, keep_prob)  
  91.   
  92.   hidden2 = nn_layer(dropped1, 500300'layer2')  
  93.   
  94.   with tf.name_scope('dropout2'):  
  95.     tf.scalar_summary('dropout_keep_probability2', keep_prob)  
  96.     dropped2 = tf.nn.dropout(hidden2, keep_prob)  
  97.   
  98.   y = nn_layer(dropped2, 30010'layer3', act=tf.nn.softmax)  
  99.   
  100.   with tf.name_scope('cross_entropy'):  
  101.     diff = y_ * tf.log(y)  
  102.     with tf.name_scope('total'):  
  103.       cross_entropy = -tf.reduce_mean(diff)  
  104.     tf.scalar_summary('cross entropy', cross_entropy)  
  105.   
  106.   with tf.name_scope('train'):  
  107.     train_step = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(  
  108.         cross_entropy)  
  109.   
  110.   with tf.name_scope('accuracy'):  
  111.     with tf.name_scope('correct_prediction'):  
  112.       correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))  
  113.     with tf.name_scope('accuracy'):  
  114.       accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  115.     tf.scalar_summary('accuracy', accuracy)  
  116.   
  117.   # Merge all the summaries and write them out to /tmp/mnist_logs (by default)  
  118.   merged = tf.merge_all_summaries()  
  119.   train_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/train',sess.graph)  
  120.   test_writer = tf.train.SummaryWriter(FLAGS.summaries_dir + '/test')  
  121.   tf.initialize_all_variables().run()  
  122.   
  123.   #  
  124.   for i in range(FLAGS.max_steps):  
  125.     if i % 10 == 0:  # Record summaries and test-set accuracy  
  126.       summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))  
  127.       test_writer.add_summary(summary, i)  
  128.       print('Accuracy at step %s: %s' % (i, acc))  
  129.     else:  # Record train set summaries, and train  
  130.       summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))  
  131.       train_writer.add_summary(summary, i)  
  132.   
  133.   
  134. def main(_):  
  135.   if tf.gfile.Exists(FLAGS.summaries_dir):  
  136.     tf.gfile.DeleteRecursively(FLAGS.summaries_dir)  
  137.   tf.gfile.MakeDirs(FLAGS.summaries_dir)  
  138.   train()  
  139.   
  140.   
  141. if __name__ == '__main__':  
  142.   tf.app.run()  

  1. <span style="font-size:14px;">variable_summaries</span>  

函数可以用在其他地方,打开目录定位/tmp/mnist_logs图表中可以有两条曲线,一个是是训练一个是测试

注意:如果保存数据过于频繁,会显著增加运行时间!毕竟硬盘读取的速度太慢,即使是SSD也不必要全部保存数据(程序速度能快一点是一点),一般的做法是每个100---1000步保存一下数据供图表显示即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值