1. 程式人生 > 其它 >TensorFlow模擬簡單線性模型小栗子

TensorFlow模擬簡單線性模型小栗子

作者:趙 慧

編輯:李文臣

TensorFlow是什麼

官方英文介紹:TensorFlow™ is an open source software library for numerical computation using data flow graphs.

TensorFlow是谷歌2015年開源的一個人工智慧平臺。就如命名一樣,TensorFlow為張量從圖的一端流動到另一端計算過程。TensorFlow是將複雜的資料結構傳輸至人工智慧神經網中進行分析和處理過程的系統。TensorFlow可被用於語音識別或影象識別等多項機器深度學習領域,它可在小到一部智慧手機、大到數千臺數據中心伺服器的各種裝置上執行。與TensorFlow類似的庫還有Caffe,Theano, MXNet.

TensorFlow的核心元件:

1. 張量(Tensor):大部分針對向量和矩陣

2. 基於張量的各種操作:比如矩陣乘法、計算均值方差等,本質上是從輸入變數到輸出變數的一個對映,

3. 計算圖(Computation Graph):

4. 自動微分(Automatic Differentiation)工具:即定義了一連串的運算後,計算機就可以自動幫你計算整個輸入輸出間的梯度,

5. BLAS、cuBLAS、cuDNN等拓展包

TensorFlow框架

本文的標題和內容牽都涉及到 TensorFlow,僅僅是因為它是可以選用的工具之一,像Keras等等其他的框架都可以實現文章中想要的模型。本人無工具上的偏好,所以就當是拿 TensorFlow 舉一個小小的例子。

從市面上的書籍和文章我們可以瞭解到TensorFlow 貌似是為深度學習而生的,好像不做些影象識別、機器人等深度學習專案就觸不到TensorFlow,自己一直是這樣固執的認為, 所以做模型的時候對TensorFlow都是視而不見的態度。

模擬線性模型

文中通過模擬產生資料,構造簡單的線性模型,使用TensorFlow工具,利用梯度下降演算法,估計模型係數,給出模擬的收斂效果;同時,我們使用著名的鳶尾花資料集來小試牛刀,so,let’s begin , just do it !

#首先載入我們將要用到的庫
import tensorflow as tf
import numpy as np

#模擬產生資料
x_data = np.random.rand(1000).astype(np.float32)

#公式
y_data = 0.5 * x_data**2 + 0.3

下面看看我們畫圖看看資料到底長成什麼樣子,是不是美麗的:

從圖中我們是可以看出二次趨勢的,下面開始我們的tensorflow模擬過程。

#產生TensorFlow結構的資料
###create tensorflow Weights and biases ###
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0)
biases = tf.Variable(tf.zeros([1])

#公式和上面的一樣
###generate formula as above
y = Weights*x_data**2 + biases

#優化過程
#首先,定義損失函式(這裡使用MSE)
###define loss function
loss = tf.reduce_mean(tf.square(y-y_data))

#使用梯度下降最優化損失函式,步長暫定為0.05
optimizer = tf.train.GradientDescentOptimizer(0.05)
#極小化損失函式
train = optimizer.minimize(lose)

#初始化變數
init = tf.global_variables_initializer()

#結束建立tensorflow結構,並且run起來
sess = tf.Session()
sess.run(init)

#我們選擇迭代次數最大為500次,部分列印優化得到的結果
for step in range(501):
    sess.run(train)
    if step % 20 :
        print(step,sess.run(Weights),sess.run(biases))

#列印部分迭代結果如下:

0 [ 0.45762387] [ 0.31559378]

20 [ 0.46390951] [ 0.31328076]

40 [ 0.46926278] [ 0.3113108]

60 [ 0.47382206] [ 0.30963311]

80 [ 0.477705] [ 0.3082042]

100 [ 0.48101205] [ 0.30698729]

120 [ 0.48382849] [ 0.30595091]

140 [ 0.48622724] [ 0.30506817]

160 [ 0.48827016] [ 0.30431643]

180 [ 0.49001008] [ 0.30367616]

200 [ 0.49149185] [ 0.30313087]

220 [ 0.49275389] [ 0.30266646]

240 [ 0.49382871] [ 0.30227098]

260 [ 0.49474409] [ 0.30193409]

280 [ 0.49552372] [ 0.30164719]

300 [ 0.49618763] [ 0.30140293]

320 [ 0.49675313] [ 0.30119479]

340 [ 0.49723473] [ 0.30101761]

360 [ 0.49764487] [ 0.30086669]

380 [ 0.49799421] [ 0.3007381]

400 [ 0.49829179] [ 0.30062863]

看看預測效果

pre = sess.run(Weights) * x_data**2 + sess.run(biases)

為方便將我們的預測結果與原始資料做對比,選擇迭代次數變化過程中擬合效果的視覺化展示:

import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(20,10))

plt.plot(x_data,pre,'bo',label="Predicted data",color='red')
plt.plot(x_data,y_data,'bo',label="Original data",color='blue')
###open the grid###
plt.grid(True)

plt.legend(bbox_to_anchor=(1.0,1),fontsize=23,loc=1,borderaxespad=0.)
plt.title("Linear Model:iteration 100 times : y = 0.5*x^2 + 0.3",fontsize=25)

plt.show()

迭代100次效果:

迭代200次效果:

迭代300次效果:

迭代400次效果:

迭代500次效果:

固定學習率,從迭代次數逐漸增加的過程中可以看出效果也是逐漸趨向完美擬合。

實現一個小栗子

下面我們使用著名的鳶尾花資料集進行例項分析:

讀取資料集

import pandas as pd

iris = pd.read_csv('iris.csv')
#檢視資料
iris.head()
y_data = np.array(iris["Sepal.Length"]) #萼片長度
x = np.array(iris["Petal.Width"])   #花瓣寬度

#初始化權重和偏差
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))

biases = tf.Variable(tf.zeros([1]))

y = Weights * x + biases

loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.05)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

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

Loss = pd.Series(np.arange(400,dtype = float))
for step in range(301):
    sess.run(train)
    Loss[step] = sess.run(loss)
    if step % 40 == 0:
        print(step,sess.run(Weights),sess.run(biases),"MSE:",sess.run(loss))

得到部分迭代結果如下:

0 [0.57750076] [0.61055863] MSE: 20.8943

20 [2.08994746] [2.9580822] MSE: 1.20182

40 [1.68378949] [3.5774076] MSE: 0.65115

60 [1.413679] [3.98509526] MSE: 0.411057

80 [1.23531616] [4.25429916] MSE: 0.30637

100[1.11753857] [4.43206167] MSE:0.260724

120[1.03976703] [4.54944229] MSE:0.240821

140[0.98841262] [4.62695217] MSE:0.232142

160[0.95450181] [4.67813396] MSE:0.228358

180[0.93210948] [4.71193075] MSE:0.226708

200[0.91732353] [4.73424721] MSE:0.225989

220[0.90755975] [4.74898386] MSE:0.225675

240[0.90111274] [4.7587142] MSE:0.225538

260[0.89685577] [4.7651391] MSE:0.225479

280[0.89404517] [4.76938105] MSE:0.225453

300[0.89218873] [4.77218294] MSE:0.225441

320[0.8909629] [4.77403307] MSE:0.225436

340[0.89015353] [4.77525473] MSE:0.225434

360[0.88961929] [4.77606106] MSE:0.225433

380[0.88926637] [4.77659416] MSE:0.225433

400[0.88903302] [4.77694607] MSE:0.225433

fig,ax = plt.subplots(figsize=(20,10))
Loss.plot(ylim = [0,20])
plt.show()
pre = sess.run(Weights)*x + sess.run(biases)

import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(20,10))

#"x-",go-,rs,bo,+-
plt.plot(x,pre,'bo',label="Predicted data",color='red')

#'#00FF7F'
plt.plot(x,y_data,"bo",label="Original data",color='blue')
#plt.plot(x_data,y,"bo",label="Original data",color='green')#'#00FF7F'
'''open the grid'''
plt.grid(True)

plt.legend(bbox_to_anchor=(1.0,1),fontsize=25,loc=1,borderaxespad=0.)
plt.show()

可以看出簡單線性模型對鳶尾花資料集擬合效果還是不錯的。實際中我們可以使用花瓣寬度x對萼片長度y進行大體的預測。

結束語

一個使用Tensorflow應用於傳統統計模型的小例子就這樣告成了,歡迎指正。