用TensorFlow訓練線性和邏輯回歸模型
這一節結合前面介紹的所有TensorFlow概念來訓練線性和邏輯回歸模型,使用玩具數據集。
用TensorFlow訓練模型
假如我們指明了數據點和標簽的容器,定義了張量操作的損失函數。添加了優化器節點到計算圖,它可以用來計算梯度下降。我們如何重復進行梯度下降來學習數據集呢?
答案是用Python for-循環。代碼塊 Example 3-10說明這個簡單的學習過程。注意為了簡化教學我們不使用 minibatches 。后面訓練大數據集時會用minibatches。
使用TensorFlow的線性回歸
這一節我們用Tensor‐Flow 定義線性回歸,并學習它的權重。任務很直接,你可以不用TensorFlow完成。但是,使用TensorFlow 是很好的練習因為它可以將我們學習過的概念一起使用。
用TensorFlow定義和訓練線性回歸
線性回歸模型很簡單:
y = wx + b
這里 w 和 b 是我們要學習的權重。我們轉換這些權重至tf.Variable對象。然后用張量操作來構建損失函數 L2 loss:
?( x, y)=( y ? wx ? b) 2
List3-24的代碼用TensorFlow實現這些數學操作。添加tf.train.AdamOp 優化器來學習以及tf.summary操作來合用TensorBoard。
#List3-24. Defining a linear regression model
#定義模型函數
def model(x,w,b):
??? return tf.multiply(x,w)+b
def loss_fun(x,y,w,b):
??? err = model(x,w,b)-y
??? squared_err = tf.square(err)
??? return tf.reduce_mean(squared_err)
def grad(x,y,w,b):
??? with tf.GradientTape() as tape:
??????? loss_ = loss_fun(x,y,w,b)
??? return tape.gradient(loss_,[w,b])
List3-25 訓練模型 (不用 minibatches).
#List3-25. Training the linear regression model
w = tf.Variable(np.random.randn(),tf.float32)
b = tf.Variable(0.0,tf.float32)
#設置迭代次數和學習率
train_epochs = 100
learning_rate = 0.01
loss = []
y_pred=[]
count = 0
display_count = 10 #控制顯示粒度的參數,每訓練10個樣本輸出一次損失值
#開始訓練,輪數為epoch,采用SGD隨機梯度下降優化方法
for epoch in range(train_epochs):
??? for xs,ys in zip(x_np,y_np):
??????? #計算損失,并保存本次損失計算結果
??????? #rand_index = np.random.choice(100)
??????? #rand_x = tf.cast([x_vals[rand_index]],dtype=tf.float32)
??????? #rand_y =? tf.cast([y_vals[rand_index]],dtype=tf.float32)
??????? loss_ =loss_fun(xs,ys,w,b)
??????? loss.append(loss_)
??????? #計算當前[w,b]的梯度
??????? delta_w,delta_b = grad(xs,ys,w,b)
??????? change_w = delta_w * learning_rate
??????? change_b = delta_b * learning_rate
??????? w.assign_sub(change_w)
??????? b.assign_sub(change_b)
??????? #訓練步數加1
??????? count = count +1
??????? if count % display_count == 0:
??????????? print('train epoch : ','%02d'%(epoch+1),'step:%03d' % (count),'loss= ','{:.9f}'.format(loss_))
為線性回歸取梯度
線性回歸模型的方程為 y = wx + b
其中 w, b是可學習權重。我們前面提過,這個系統的損失是 ? =( y ? wx ? b)2。可以用上些矩陣微積分來計算可學習參數的梯度:
?????????????????
以及
???????????????????
這些方程僅給有好奇心讀者參考。我們不會系統的教如何求損失函數的微分。