# 可視化 TensorBoard 中的圖
監視和排除機器學習算法可能是一項艱巨的任務,尤其是在您知道結果之前必須等待很長時間才能完成訓練。為了解決這個問題,TensorFlow 包含一個名為 TensorBoard 的計算圖可視化工具。使用 TensorBoard,即使在訓練期間,我們也可以可視化和繪制重要值(損失,準確率,批次訓練時間等)。
## 做好準備
為了說明我們可以使用 TensorBoard 的各種方法,我們將從[第 3 章](../Text/20.html),線性回歸中的線性回歸方法的 TensorFlow 方法重新實現線性回歸模型。我們將生成帶有錯誤的線性數據,并使用 TensorFlow 損失和反向傳播來匹配數據線。我們將展示如何監控數值,值集的直方圖以及如何在 TensorBoard 中創建圖像。
## 操作步驟
1. 首先,我們將加載腳本所需的庫:
```py
import os
import io
import time
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
```
1. 我們現在將初始化一個會話并創建一個可以將 TensorBoard 摘要寫入`tensorboard`文件夾的摘要編寫器:
```py
sess = tf.Session()
# Create a visualizer object
summary_writer = tf.summary.FileWriter('tensorboard', sess.graph)
```
1. 我們需要確保`tensorboard`文件夾存在,以便摘要編寫者編寫`tensorboard`日志:
```py
if not os.path.exists('tensorboard'):
os.makedirs('tensorboard')
```
1. 我們現在將設置模型參數并生成模型的線性數據。請注意,由于我們生成數據的方式,我們的真實斜率值是`2`。我們將隨著時間的推移想象出變化的斜率,并看到它接近真正的價值:
```py
batch_size = 50
generations = 100
# Create sample input data
x_data = np.arange(1000)/10\.
true_slope = 2\.
y_data = x_data * true_slope + np.random.normal(loc=0.0, scale=25, size=1000)
```
1. 接下來,我們將數據集拆分為訓練和測試集:
```py
train_ix = np.random.choice(len(x_data), size=int(len(x_data)*0.9), replace=False)
test_ix = np.setdiff1d(np.arange(1000), train_ix)
x_data_train, y_data_train = x_data[train_ix], y_data[train_ix]
x_data_test, y_data_test = x_data[test_ix], y_data[test_ix]
```
1. 現在我們可以創建占位符,變量,模型運算,損失和優化操作:
```py
x_graph_input = tf.placeholder(tf.float32, [None])
y_graph_input = tf.placeholder(tf.float32, [None])
# Declare model variables
m = tf.Variable(tf.random_normal([1], dtype=tf.float32), name='Slope')
# Declare model
output = tf.multiply(m, x_graph_input, name='Batch_Multiplication')
# Declare loss function (L1)
residuals = output - y_graph_input
l2_loss = tf.reduce_mean(tf.abs(residuals), name="L2_Loss")
# Declare optimization function
my_optim = tf.train.GradientDescentOptimizer(0.01)
train_step = my_optim.minimize(l2_loss)
```
1. 我們現在可以創建一個 TensorBoard 操作來匯總標量值。我們將總結的標量值是模型的斜率估計值:
```py
with tf.name_scope('Slope_Estimate'):
tf.summary.scalar('Slope_Estimate', tf.squeeze(m))
```
1. 我們可以添加到 TensorBoard 的另一個摘要是直方圖摘要,它在張量中輸入多個值并輸出圖和直方圖:
```py
with tf.name_scope('Loss_and_Residuals'):
tf.summary.histogram('Histogram_Errors', tf.squeeze(l1_loss))
tf.summary.histogram('Histogram_Residuals', tf.squeeze(residuals))
```
1. 創建這些摘要操作后,我們需要創建一個將所有摘要組合在一起的摘要合并操作。然后我們可以初始化模型變量:
```py
summary_op = tf.summary.merge_all()
# Initialize Variables
init = tf.global_variables_initializer()
sess.run(init)
```
1. 現在,我們可以訓練線性模型并編寫每一代的摘要:
```py
for i in range(generations):
batch_indices = np.random.choice(len(x_data_train), size=batch_size)
x_batch = x_data_train[batch_indices]
y_batch = y_data_train[batch_indices]
_, train_loss, summary = sess.run([train_step, l2_loss, summary_op],
feed_dict={x_graph_input: x_batch,
y_graph_input: y_batch})
test_loss, test_resids = sess.run([l2_loss, residuals], feed_dict={x_graph_input: x_data_test, y_graph_input: y_data_test})
if (i+1)%10==0:
print('Generation {} of {}. Train Loss: {:.3}, Test Loss: {:.3}.'.format(i+1, generations, train_loss, test_loss))
log_writer = tf.train.SummaryWriter('tensorboard')
log_writer.add_summary(summary, i)
```
1. 為了將最終的線性擬合圖與 TensorBoard 中的數據點放在一起,我們必須以`protobuf`格式創建圖的圖像。為此,我們將創建一個輸出`protobuf`圖像的函數:
```py
def gen_linear_plot(slope):
linear_prediction = x_data * slope
plt.plot(x_data, y_data, 'b.', label='data')
plt.plot(x_data, linear_prediction, 'r-', linewidth=3, label='predicted line')
plt.legend(loc='upper left')
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
return(buf)
```
1. 現在,我們可以創建`protobuf`圖像并將其添加到 TensorBoard:
```py
# Get slope value
slope = sess.run(m)
# Generate the linear plot in buffer
plot_buf = gen_linear_plot(slope[0])
# Convert PNG buffer to TF image
image = tf.image.decode_png(plot_buf.getvalue(), channels=4)
# Add the batch dimension
image = tf.expand_dims(image, 0)
# Add image summary
image_summary_op = tf.summary.image("Linear_Plot", image)
image_summary = sess.run(image_summary_op)
log_writer.add_summary(image_summary, i)
log_writer.close()
```
Be careful writing image summaries too often to TensorBoard. For example, if we were to write an image summary every generation for 10,000 generations, that would generate 10,000 images worth of summary data. This tends to eat up disk space very quickly.
## 更多
1. 由于我們要從命令行運行描述的 python 腳本,我們打開命令提示符并運行以下命令:
```py
$ python3 using_tensorboard.py
Run the command: $tensorboard --logdir="tensorboard" Then navigate to http://127.0.0.0:6006
Generation 10 of 100\. Train Loss: 20.4, Test Loss: 20.5\.
Generation 20 of 100\. Train Loss: 17.6, Test Loss: 20.5\.
Generation 90 of 100\. Train Loss: 20.1, Test Loss: 20.5\.
Generation 100 of 100\. Train Loss: 19.4, Test Loss: 20.5\.
```
1. 然后我們將運行前面指定的命令來啟動 tensorboard:
```py
$ tensorboard --logdir="tensorboard" Starting tensorboard b'29' on port 6006 (You can navigate to http://127.0.0.1:6006)
```
以下是我們在 TensorBoard 中可以看到的示例:

圖 1:標量值,我們的斜率估計,在張量板中可視化
在這里,我們可以看到我們的標量總結的 100 代的繪圖,斜率估計。事實上,我們可以看到它確實接近`2`的真正價值:

圖 2:在這里,我們可視化模型的誤差和殘差的直方圖
上圖顯示了查看直方圖摘要的一種方法,可以將其視為多個折線圖:

圖 3:張量板中插入的圖片
前面是我們以`protobuf`格式放入的最終擬合和數據點圖,并插入到 TensorBoard 中的圖像摘要中。
- TensorFlow 入門
- 介紹
- TensorFlow 如何工作
- 聲明變量和張量
- 使用占位符和變量
- 使用矩陣
- 聲明操作符
- 實現激活函數
- 使用數據源
- 其他資源
- TensorFlow 的方式
- 介紹
- 計算圖中的操作
- 對嵌套操作分層
- 使用多個層
- 實現損失函數
- 實現反向傳播
- 使用批量和隨機訓練
- 把所有東西結合在一起
- 評估模型
- 線性回歸
- 介紹
- 使用矩陣逆方法
- 實現分解方法
- 學習 TensorFlow 線性回歸方法
- 理解線性回歸中的損失函數
- 實現 deming 回歸
- 實現套索和嶺回歸
- 實現彈性網絡回歸
- 實現邏輯回歸
- 支持向量機
- 介紹
- 使用線性 SVM
- 簡化為線性回歸
- 在 TensorFlow 中使用內核
- 實現非線性 SVM
- 實現多類 SVM
- 最近鄰方法
- 介紹
- 使用最近鄰
- 使用基于文本的距離
- 使用混合距離函數的計算
- 使用地址匹配的示例
- 使用最近鄰進行圖像識別
- 神經網絡
- 介紹
- 實現操作門
- 使用門和激活函數
- 實現單層神經網絡
- 實現不同的層
- 使用多層神經網絡
- 改進線性模型的預測
- 學習玩井字棋
- 自然語言處理
- 介紹
- 使用詞袋嵌入
- 實現 TF-IDF
- 使用 Skip-Gram 嵌入
- 使用 CBOW 嵌入
- 使用 word2vec 進行預測
- 使用 doc2vec 進行情緒分析
- 卷積神經網絡
- 介紹
- 實現簡單的 CNN
- 實現先進的 CNN
- 重新訓練現有的 CNN 模型
- 應用 StyleNet 和 NeuralStyle 項目
- 實現 DeepDream
- 循環神經網絡
- 介紹
- 為垃圾郵件預測實現 RNN
- 實現 LSTM 模型
- 堆疊多個 LSTM 層
- 創建序列到序列模型
- 訓練 Siamese RNN 相似性度量
- 將 TensorFlow 投入生產
- 介紹
- 實現單元測試
- 使用多個執行程序
- 并行化 TensorFlow
- 將 TensorFlow 投入生產
- 生產環境 TensorFlow 的一個例子
- 使用 TensorFlow 服務
- 更多 TensorFlow
- 介紹
- 可視化 TensorBoard 中的圖
- 使用遺傳算法
- 使用 k 均值聚類
- 求解常微分方程組
- 使用隨機森林
- 使用 TensorFlow 和 Keras