TensorFlow-3-TensorBoard: Visualizing Learning

来源:互联网 发布:网页版游戏源码 编辑:程序博客网 时间:2024/05/20 02:27
模型的保存和载入:
模型的保存:saver.save 保存各种构建模型graph的操作(矩阵相乘,sigmoid等等....)
saver = tf.train.Saver() # 生成saver
with tf.Session() as sess:
     sess.run(tf.global_variables_initializer()) # 先对模型初始化
     # 然后将数据丢入模型进行训练blablabla
     # 训练完以后,使用saver.save 来保存
     saver.save(sess, "save_path/file_name") #file_name如果不存在的话,会自动创建
模型载入:saver.restore
saver = tf.train.Saver()
with tf.Session() as sess:
#参数可以进行初始化,也可不进行初始化。即使初始化了,初始化的值也会被restore的值给覆盖 sess.run(tf.global_variables_initializer())
saver.restore(sess, "save_path/file_name") #会将已经保存的变量值resotre到 变量中。

TensorBoard的使用
tf.summary.scalar('loss',loss )
记录 Learning rate, loss 随时间的变化, 并可以给标签,像'learning rate' 或者'loss function'.

tf.summary.histogram
像查看activation的分布,脱离某个特殊的层,或者gradients或者weights的变化

tf.summary.merge_all
结合所有记录的信息使用

tf.summary.FileWriter.
将summary的信息写到磁盘上.
可选择的传一个Graph到FileWriter中. 如果传入了, TensorBoard将会可视化你的图.

使用顺序:
  1. tf.summary.scalar和tf.summary.histogram收集信息
  2. 收集过后 tf.summary.merge_all
  3. 初始化FileWriter
  4. Session去run结合后的summary
  5. FileWirter.add_summary(summary, i),添加summary

with tf.name_scope('accuracy'):
     with tf.name_scope('correct_prediction'):
          correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
     with tf.name_scope('accuracy'):
          accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 1
tf.summary.scalar('accuracy', accuracy)

# Merge all the summaries and write them out to /tmp/mnist_logs (by default)
# 2
merged = tf.summary.merge_all()
# 3
train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train',sess.graph)
test_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/test')
tf.global_variables_initializer().run()

# Train the model, and also write summaries.
# Every 10th step, measure test-set accuracy, and write test summaries
# All other steps, run train_step on training data, & add training summaries

......

for i in range(FLAGS.max_steps):
     if i % 10 == 0: # Record summaries and test-set accuracy
          # 4
          summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))
          # 5
    test_writer.add_summary(summary, i)
    print('Accuracy at step %s: %s' % (i, acc))
     else: # Record train set summaries, and train
          summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
          train_writer.add_summary(summary, i)

添加变量,dropout,添加层的写法
官方文档中提供的

def variable_summaries(var):
  """Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
  with tf.name_scope('summaries'):
    mean = tf.reduce_mean(var)
    tf.summary.scalar('mean', mean)
    with tf.name_scope('stddev'):
      stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
    tf.summary.scalar('stddev', stddev)
    tf.summary.scalar('max', tf.reduce_max(var))
    tf.summary.scalar('min', tf.reduce_min(var))
    tf.summary.histogram('histogram', var)

def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
  """Reusable code for making a simple neural net layer.

  It does a matrix multiply, bias add, and then uses relu to nonlinearize.
  It also sets up name scoping so that the resultant graph is easy to read,
  and adds a number of summary ops.
  """
  # Adding a name scope ensures logical grouping of the layers in the graph.
  with tf.name_scope(layer_name):
    # This Variable will hold the state of the weights for the layer
    with tf.name_scope('weights'):
      weights = weight_variable([input_dim, output_dim])
      variable_summaries(weights)
    with tf.name_scope('biases'):
      biases = bias_variable([output_dim])
      variable_summaries(biases)
    with tf.name_scope('Wx_plus_b'):
      preactivate = tf.matmul(input_tensor, weights) + biases
      tf.summary.histogram('pre_activations', preactivate)
    activations = act(preactivate, name='activation')
    tf.summary.histogram('activations', activations)
    return activations

hidden1 = nn_layer(x, 784, 500, 'layer1')

with tf.name_scope('dropout'):
  keep_prob = tf.placeholder(tf.float32)
  tf.summary.scalar('dropout_keep_probability', keep_prob)
  dropped = tf.nn.dropout(hidden1, keep_prob)

# Do not apply softmax activation yet, see below.
y = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)

自己跳的坑

如果想要获得合并的信息,必须在run的时候,传输入进去,否则会报错:
InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [1000,625]
merged = tf.summary.merge_all()
for i in range(500):
  # 7. here to determine the keeping probability
  sess.run(train_step, feed_dict={xs: X_train, ys: y_train, keep_prob: 0.5}) # 解决问题
  if i % 50 == 0:
  # record loss
  train_result = sess.run(merged, feed_dict={xs: X_train, ys: y_train, keep_prob: 1}) # record result, so don't dropout
  test_result = sess.run(merged, feed_dict={xs: X_test, ys: y_test, keep_prob: 1})
  train_writer.add_summary(train_result, i)
  test_writer.add_summary(test_result, i)


当只获取一个tf.summary.scalar时,直接run就可以,可以不传输入:
dev_summary = tf.summary.scalar('dev_accuracy', accuracy)
dev_summary = session.run(dev_summary)
writer.add_summary(dev_summary,epoches)
writer.flush()


查看 TensorBoard的写法
writer = tf.summary.FileWriter("D://WorkSpace//DP_workspace//TensorflowTest//log",tf.get_default_graph()) 
进入命令行:
tensorboard --logdir=D://WorkSpace//DP_workspace//TensorflowTest//log # !!must write in this way
进入chrome,输入:
http://localhost:6006/