1. 程式人生 > >[ML]簡單的Normal Equation對數據點進行線性回歸

[ML]簡單的Normal Equation對數據點進行線性回歸

線上 and 計算 normal .com .cn spa numpy plot

註明:本文僅作為記錄本人的日常學習歷程而存在。

Normal Equation和上篇介紹的方法相比,簡單許多。具體公式見吳恩達老師的coursera視頻

1.

generate_data用來生成實驗中所用到的數據,數據總體分布在斜率為10-30之間隨機取值,截距為200-5000之間隨機取值的直線上

compute函數用來計算出目標直線參數:

import numpy as np
import matplotlib.pyplot as plt
def compute(X,Y):
    return (X.T.dot(X))**(-1)*(X.T)*Y
def generate_data(data_size):
    x 
= np.random.randint(-250,250,size=data_size) y = [] for i in range(data_size): y.append(x[i]*np.random.randint(10,30)+np.random.randint(200,5000)) return (x,y)

2.

進行計算。

data_size = 500
(xx,yy) = generate_data(data_size)
#plt.plot(x,y,‘rx‘)
x = [[1,xx[i]] for i in range(data_size)]
X = np.matrix(x).reshape((data_size,2))
Y 
= np.matrix(yy).reshape((data_size,1)) theta = compute(X,Y) theta = theta.getA() print(theta)

3.

可視化:

result_x = np.linspace(-250,250,data_size)
result_y = theta[1] * result_x + theta[0]
plt.plot(result_x,result_y)
plt.plot(xx,yy,rx)

4.最終結果:

技術分享

[ML]簡單的Normal Equation對數據點進行線性回歸