tensorboard入門級測試
阿新 • • 發佈:2018-11-18
esc figure import del 圖像 mask 模型 orm writer
Tensorboard
tensorboard用以圖形化展示我們的代碼結構和圖形化訓練誤差等,輔助優化程序
參考鏈接:www.cnblogs.com/fydeblog/p/7429344.html
微代碼測試
代碼全文
import tensorflow as tf with tf.name_scope('graph') as scope: a = tf.constant([[3,4]],name = 'a') b = tf.constant([[5],[6]],name = 'b') product = tf.matmul(a,b,name='product') sess = tf.Session() writer = tf.summary.FileWriter('./tensorflow/',sess.graph) init = tf.global_variables_initializer() sess.run(init)
啟動tensorboard
運行代碼之後可以在目錄./tensorboard/
下看到生成了一個文件,用於啟動tensorboard。執行tensorboard --logdir ./tensorflow/
,打開瀏覽器127.0.0.1:6006
,可以看到視圖
註:要保證該文件夾下只有一個文件
雙擊graph可以進一步打開,這就是我們這段微代碼的結構
進階
這裏我們基於之前的一段代碼,與tensorboard相結合來看下效果。
前文鏈接:https://www.cnblogs.com/maskerk/p/9973503.html
代碼全文
import tensorflow as tf import matplotlib.pyplot as plt import numpy as np #樣本數據 with tf.name_scope('sample-data'): x_train = np.linspace(-1,1,300)[:,np.newaxis] noise = np.random.normal(0, 0.1, x_train.shape) y_train = x_train * 3 + noise + 0.8 # with tf.name_scope('hold-data'): x = tf.placeholder(tf.float32, [None, 1]) y = tf.placeholder(tf.float32, [None, 1]) #線性模型 with tf.name_scope('line-model'): W = tf.Variable([0.1],dtype = tf.float32,name='W') #添加變量W到tensorboard的Distributions下 tf.summary.histogram('Weight',W) b = tf.Variable([0.1],dtype = tf.float32,name='b') line_model = W * x + b #添加變量b到tensorboard的Distributions下 tf.summary.histogram('bias',b) #損失模型 with tf.name_scope("loss-model"): loss = tf.reduce_sum(tf.square(line_model - y)) #添加變量loss到tensorboard的Scalars下 tf.summary.scalar("loss",loss) #創建優化器 with tf.name_scope("optimizer-model"): optimizer = tf.train.GradientDescentOptimizer(0.001) train = optimizer.minimize(loss) #初始化變量 with tf.name_scope("init-model"): init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) # 繪制樣本數據 fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.scatter(x_train, y_train) plt.ion() plt.show() plt.pause(1) #將所有的summary全部保存磁盤 merged = tf.summary.merge_all() #tensorboard所需數據寫入文件 writer = tf.summary.FileWriter('./tensorflow/',sess.graph) #訓練100次 for i in range(100): if i % 10 == 0: #每隔10次打印1次成果 print(i) print('W:%s b:%s' % (sess.run(W),sess.run(b))) print('loss:%s' % (sess.run(loss,{x:x_train,y:y_train}))) #繪制擬合直線 try: ax.lines.remove(lines[0]) except Exception: pass lines = ax.plot(x_train, sess.run(W)*x_train+sess.run(b), 'r-', lw=5) plt.pause(1) sess.run(train,{x:x_train,y:y_train}) #向tensorboard添加數據 rs = sess.run(merged,{x:x_train,y:y_train}) writer.add_summary(rs,i) # 打印訓練100次後的成果 print('---') print('W:%s b:%s' % (sess.run(W),sess.run(b))) print('loss:%s' % (sess.run(loss,{x:x_train,y:y_train})))
相比前文,這裏添加了兩部分
1.擬合直線的動態變化圖像
2.tensorboard展現數據變化過程
啟動tensorboard
tensorboard --logdir ./tensorflow/
可以看到loss(誤差大小)的變化曲線
權重值W和偏差b的變化曲線(y = W * x + b)
tensorboard入門級測試