Tensorflow機器學習入門——網路可視化TensorBoard ...
一、在代碼中標記要顯示的各種量
tensorboard各函數的作用和用法請參考:https://www.cnblogs.com/lyc-seu/p/8647792.html
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import os #設置當前工作目錄 os.chdir(r'H:\Notepad\Tensorflow') def add_layer(inputs, in_size, out_size, n_layer, activation_function=None): layer_name = 'layer%s' % n_layer with tf.name_scope(layer_name): Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W') biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='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, ) #histogram用來顯示訓練過程中變數的分佈情況 tf.summary.histogram(layer_name + '/weights', Weights) tf.summary.histogram(layer_name + '/biases', biases) tf.summary.histogram(layer_name + '/outputs', outputs) return outputs #數據 x_data = np.linspace(-1,1,300)[:, np.newaxis] noise = np.random.normal(0, 0.05, x_data.shape) y_data = 5*np.square(x_data) - 0.5 + noise #輸入 with tf.name_scope('inputs'): xs = tf.placeholder(tf.float32, [None, 1], name='x_input') ys = tf.placeholder(tf.float32, [None, 1], name='y_input') #3層網路 l1 = add_layer(xs, 1, 10, 1,activation_function=tf.nn.relu) l2 = add_layer(l1, 10, 10,2, activation_function=tf.nn.relu) prediction = add_layer(l2, 10, 1,3, activation_function=None) #損失與訓練 with tf.name_scope('loss'): loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1])) tf.summary.scalar('loss-haha', loss) with tf.name_scope('train'): train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) #運行 init = tf.global_variables_initializer() #merge_all 可以將所有summary全部保存到磁碟,以便tensorboard顯示。 merged = tf.summary.merge_all() with tf.Session() as sess: sess.run(init)
#FileWriter指定一個文件用來保存圖。可以調用其add_summary()方法將訓練過程數據保存在filewriter指定的文件中 writer = tf.summary.FileWriter("logs/", sess.graph)#輸出Graph for i in range(10000): sess.run(train_step, feed_dict={xs: x_data, ys: y_data}) if i % 50 == 0: result = sess.run(merged,feed_dict={xs: x_data, ys: y_data}) writer.add_summary(result, i)
二、在log文件夾所在目錄打開cmd,並輸入‘ tensorboard --logdir=logs ’
三、在Google Chrome瀏覽器中輸入cmd中給出的網址: http://Fengqiao_x:6006