1. 程式人生 > >TensorFlow入門教程:13:訓練過程的視覺化分析

TensorFlow入門教程:13:訓練過程的視覺化分析

在這裡插入圖片描述 活用視覺化的結果,使用真正的人類智慧,可以一目瞭然的瞭解的演算法過程中的大致過程,這就是視覺化可以帶來的結果,在機器學習結果的展示上,能畫出來的就儘量不要以數字的形式print出來,這篇文章繼續分析y=3*x + 1的收斂過程,這裡我們來使用圖形化的方式來體驗tensorflow的強大。

事前準備

關於線性迴歸的詳細,請參看:

程式碼準備

程式碼說明部分也參看如下文章:

過程確認:100次迭代,每十次確認一下擬合狀態,程式碼如下

for j in range(100):
  for i in range(100):
    sess.run(trainoperation, feed_dict={X: xdata[i], Y:ydata[i]})
  if j % 10 == 0:
    print("j = %s index = %s" %(j,index))
    plt.subplot(2,5,index) 
    plt.scatter(xdata,ydata)
    labelinfo="iteration: " + str(j)
    plt.plot(xdata,B.eval(session=sess)+W.eval(session=sess)*xdata,'b',label=labelinfo)
    plt.plot(xdata,ydata,'r',label='expected')
    plt.legend() 
    index = index + 1

示例程式碼

liumiaocn:Notebook liumiao$ cat basic-operation-8.py 
import tensorflow as tf
import numpy      as np
import os
import matplotlib.pyplot as plt

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

xdata = np.linspace(0,1,100)
ydata = 2 * xdata + 1

print("init modole ...")
X = tf.placeholder("float",name="X")
Y = tf.placeholder("float",name="Y")
W = tf.Variable(3., name="W")
B = tf.Variable(3., name="B")
linearmodel = tf.add(tf.multiply(X,W),B)
lossfunc = (tf.pow(Y - linearmodel, 2))
learningrate = 0.01

print("set Optimizer")
trainoperation = tf.train.GradientDescentOptimizer(learningrate).minimize(lossfunc)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

index = 1
print("caculation begins ...")
for j in range(100):
  for i in range(100):
    sess.run(trainoperation, feed_dict={X: xdata[i], Y:ydata[i]})
  if j % 10 == 0:
    print("j = %s index = %s" %(j,index))
    plt.subplot(2,5,index) 
    plt.scatter(xdata,ydata)
    labelinfo="iteration: " + str(j)
    plt.plot(xdata,B.eval(session=sess)+W.eval(session=sess)*xdata,'b',label=labelinfo)
    plt.plot(xdata,ydata,'r',label='expected')
    plt.legend() 
    index = index + 1

print("caculation ends ...")
print("##After Caculation: ") 
print("   B: " + str(B.eval(session=sess)) + ", W : " + str(W.eval(session=sess)))

plt.show()
liumiaocn:Notebook liumiao$

結果確認

從結果可以看到,第一個10次的迭代完成之後就已經非常好的收斂了 在這裡插入圖片描述

這樣,我們調整一下迭代的次數:從100 改為10

for j in range(10):
  for i in range(100):
    sess.run(trainoperation, feed_dict={X: xdata[i], Y:ydata[i]})
  print("j = %s index = %s" %(j,index))
  plt.subplot(2,5,index)  
  plt.scatter(xdata,ydata)
  labelinfo="iteration: " + str(j)
  plt.plot(xdata,B.eval(session=sess)+W.eval(session=sess)*xdata,'b',label=labelinfo)
  plt.plot(xdata,ydata,'r',label='expected')
  plt.legend()  
  index = index + 1

在這裡插入圖片描述

發現依然訓練逼近的過程不是很清晰,從最開始都非常清楚,仔細確認一下初始值,W的期待值是3,初始值是2,從最開始就比較準確,所以來調整一下,變成-3,再用同樣的程式碼確認一下 在這裡插入圖片描述 可以清晰地看出調整的過程已經開始逐步逼近了,W為-3的初始值的情況下,每10次迭代粒度來確認一下訓練擬合的過程: 在這裡插入圖片描述

總結

通過對訓練過程的視覺化結果確認,發現訓練的過程會受很多因素的影響,但是總體來說還是能夠收斂。tensorflow提供的函式非常強大,很多都像是積木一樣方便,通過設定諸如LearningRate這樣的值,靈活結合這些圖形視覺化的庫函式,對於初期的學習能起到很好的輔助作用。