1. 程式人生 > >TensorFlow入門教程:17:正態噪聲下的線性迴歸

TensorFlow入門教程:17:正態噪聲下的線性迴歸

在這裡插入圖片描述 這篇文章來看一下,使用加入正態分佈的噪聲之後產生的資料進行訓練,看是否能夠得到期待的結果。

事前準備

訓練資料使用如下方式生成:

xdata = np.linspace(0,1,100)
ydata = 2 * xdata + 1 + np.random.normal(20,6,xdata.shape)*0.2

示例程式碼

liumiaocn:tensorflow liumiao$ cat basic-operation-13.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 + np.random.normal(20,6,xdata.shape)*0.2

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,2*xdata + 1,'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:tensorflow liumiao$

結果確認

在這裡插入圖片描述 100次迭代之後的,線性模型如下:

##After Caculation: 
   B: 1.46369, W : 2.0256715

沒有噪聲的學習過程, 收斂的如下: 在這裡插入圖片描述

調整引數

可以看到噪聲新增之後,資料產生了一個較大的偏移量,將引數進行調整

ydata = 2 * xdata + 1 + np.random.normal(20,6,xdata.shape)*0.02

在這裡插入圖片描述

可以看到資料的分佈範圍已經較好的收窄,但是偏差仍然存在:

##After Caculation: 
   B: 1.4173651, W : 1.9516094

可以直接糾偏,線性的只需要減一個常數即可,但是這個糾偏值的算出,可以有很多的方式,這裡可以使用最簡單的方式,比如使用均值的差

糾偏: baisadjust=np.mean(ydata) - np.mean(B.eval(session=sess)+W.eval(session=sess)*xdata)

程式碼示例

liumiaocn:tensorflow liumiao$ cat basic-operation-13.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 + np.random.normal(20,6,xdata.shape)*0.02

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,2*xdata + 1,'r',label='expected')
    baisadjust=np.mean(ydata) - np.mean(B.eval(session=sess)+W.eval(session=sess)*xdata)
    plt.plot(xdata,2*xdata + 1 + baisadjust, 'y', label='adjusted')
    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:tensorflow liumiao$ 

簡單地糾偏之後,結果如下所示: 在這裡插入圖片描述

總結

這篇文章引入了另外一個概念,資料的糾偏,有噪聲,自然就有去噪的方式,也可以稱為糾偏。仔細思考之後會發現,如何獲取噪聲資料和實際期待資料之間的差值往往是實際場景中最為重要的,這篇文章引入這個概念的目的在於說明學習的過程中結果對資料的完全擬合併不一定是最好的,那個前提是資料本身就是完美資料的情況。