新的TensorFlow概念
創建簡單的機器學習系統需要學習一些新的概念。
優化器
上兩節介紹的元素已經提示了TensorFlow是如何完成機器學習的。你已學習了如何用張量操作來定義損失函數。缺少的是你不知道如何用TensorFlow進行梯度下降。盡管可以用TensorFlow元素直接用 Python定義優化算法例如梯度下降。tf.train模塊提供了很多優化算法。這些算法可以作為TensorFlow 計算圖的節點被添加。
我該使用哪個optimizer?
tf.train里有很多可能的optimizer。包括 tf.train.GradientDescentOptimizer, tf.train.MomentumOptimizer, tf.train.AdagradOptimizer, tf.train.AdamOptimizer,等。這些 optimizers有什么區別呢?幾乎所有這些優化器都基于梯度下降的思想。我們前面講的最簡單的梯度下降規則是:
W = W ? α?W
數學上,這種更新規則是很基礎的。研究者發現很多快速優化算法不需要過多的額外計算。 tf.train.AdamOptimizer是黙認相對穩健的。(很多優化器對超參數的選擇很敏感。初學者最好不要使用復雜的方法,除非掌握了不同優化算法的行為)
Summaries and file writers for TensorBoard
可視化的理解張量程序很有用。TensorFlow團隊提供了TensorBoard,可以用以這個目 的。 TensorBoard啟動網絡服務器(黙認為localhost) 來展示TensorFlow 程序。但是程序員要手工的寫日志語句。 tf.train.FileWriter() 指明TensorBoard程序的日志目錄。tf.summary 寫入TensorFlow 匯總到日志目錄。這一章我們只使用 tf.summary.scalar,它匯部標量,跟蹤損失函數的值。 tf.summary.merge_all() 是有用的日志助手合并多個匯總到一個匯總。
運行下面的命令在存放源代碼文件的目錄下創建名為“logs”的目錄。
$ mkdir logs
運行TensorBoard并傳遞“logs”目錄的位置作為參數:
#$ tensorboard --logdir=./logs
$ tensorboard --logdir=”logs”
打開瀏覽器并導航到http://localhost:6006, 這是TensorBoard的黙認URL。
您可以在 Eager Execution 中使用?tf.summary?記錄變量摘要。例如,要每 100 個訓練步驟記錄一次?loss?的摘要,請運行以下代碼:
#List3-22
logdir = "./log/"
writer = tf.summary.create_file_writer(logdir)
steps = 1000
with writer.as_default(): ?# or call writer.set_as_default() before the loop.
? for i in range(steps):
? ? step = i + 1
? ? # Calculate loss with your real train function.
? ? loss = 1 - 0.001 * step
? ? if step % 100 == 0:
? ? ? tf.summary.scalar('loss', loss, step=step)
#List3-23_using_tensorboard.py
import os
import io
import time
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# Create a visualizer object
#summary_writer = tf.summary.FileWriter('tensorboard', tf.get_default_graph())
# Create tensorboard folder if not exists
if not os.path.exists('tensorboard'):
os.makedirs('tensorboard')
logdir = "./tensorboard"
writer = tf.summary.create_file_writer(logdir)
steps = 1000
with writer.as_default():
??? for i in range(steps):
????? step = i + 1
????? loss = 1 - 0.001 * step
????? if step % 100 == 0:
??????????????? tf.summary.scalar('loss', loss, step=step)
# Wait a few seconds for user to run tensorboard commands
time.sleep(5)
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)
# Split into train/test
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]
# Declare placeholders
#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_data_train, name='Batch_Multiplication')
# Declare loss function (L1)
residuals = output - y_data_train
l1_loss = tf.reduce_mean(tf.abs(residuals), name="L1_Loss")
# Declare optimization function
#my_optim = tf.train.GradientDescentOptimizer(0.01)
#train_step = my_optim.minimize(l1_loss)
# Visualize a scalar
with tf.name_scope('Slope_Estimate'):
tf.summary.scalar('Slope_Estimate', tf.squeeze(m))
我們從命令行運行腳本?01_using_tensorboard.py
?:
$ python3
List3-23_using_tensorboard.py
我們然后啟動Tensorboard程序:
$ tensorboard --logdir="tensorboard"
然后我們導航瀏覽器到:
http://127.0.0.0:6006
我們可以指明不同的端口號?--port 6007
? (運行于端號 6007)。