tensorboard可視化(二)

  • 2019 年 10 月 5 日
  • 筆記

tensorboard可視化(二)

1.導包

import tensorflow as tf  import numpy as np  

2.make up some data

x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]  noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)  y_data = np.square(x_data) - 0.5 + noise  

3.將xs和ys包含進來,形成一個大的圖層,圖層名字叫做inputs

with tf.name_scope('inputs'):      # 為xs指定名稱x_input      xs = tf.placeholder(tf.float32, [None, 1],name='x_input')      # 為ys指定名稱y_input      ys = tf.placeholder(tf.float32, [None, 1],name='y_input')  

4.在 layer 中為 Weights, biases 設置變化圖表

# add_layer多加一個n_layer參數(表示第幾層)  def add_layer(inputs ,                in_size,                out_size,n_layer,                activation_function=None):      ## add one more layer and return the output of this layer      layer_name='layer%s'%n_layer      with tf.name_scope(layer_name):           # 對weights進行繪製圖標           with tf.name_scope('weights'):                Weights= tf.Variable(tf.random_normal([in_size, out_size]),name='W')                tf.summary.histogram(layer_name + '/weights', Weights)            # 對biases進行繪製圖標           with tf.name_scope('biases'):                biases = tf.Variable(tf.zeros([1,out_size])+0.1, name='b')                tf.summary.histogram(layer_name + '/biases', biases)           with tf.name_scope('Wx_plus_b'):                Wx_plus_b = tf.add(tf.matmul(inputs,Weights), biases)           if activation_function is None:              outputs=Wx_plus_b           else:              outputs= activation_function(Wx_plus_b)           # 對outputs進行繪製圖標           tf.summary.histogram(layer_name + '/outputs', outputs)      return outputs  

5.修改隱藏層與輸出層

# 由於我們對addlayer 添加了一個參數, 所以修改之前調用addlayer()函數的地方. 對此處進行修改:  # add hidden layer  l1= add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)  # add output  layer  prediction= add_layer(l1, 10, 1, n_layer=2, activation_function=None)

6.設置loss的變化圖

#  loss是在tesnorBorad 的event下面的, 這是由於我們使用的是tf.scalar_summary() 方法.  with tf.name_scope('loss'):      loss = tf.reduce_mean(tf.reduce_sum(          tf.square(ys - prediction), reduction_indices=[1]))      tf.summary.scalar('loss', loss)  # tensorflow >= 0.12  

7.給所有訓練圖合併

# 機器學習提升準確率  with tf.name_scope('train'):      train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 0.1表示學習效率    # 初始化  sess= tf.Session()  merged = tf.summary.merge_all()  writer = tf.summary.FileWriter("logs/", sess.graph) #  sess.run(tf.global_variables_initializer())  

8.訓練數據

for i in range(1000):     sess.run(train_step, feed_dict={xs:x_data, ys:y_data})     if i%50 == 0:        rs = sess.run(merged,feed_dict={xs:x_data,ys:y_data})        writer.add_summary(rs, i)