Python 機器學習 一元線性回歸

2021-09-26 05:05:51 字數 1284 閱讀 5239

一元線性回歸模型很簡單

y1=ax+b+ε,y1為實際值,ε為正態的誤差。

y2=ax+b,y2為**值。

ε=y1-y2。

def model(a,b,x):

return a*x+b

這裡將整組資料的**結果方差作為損失函式。

j(a,b)=sum((y1-y2)^2)/n

def cost(a,b,x,y):

# x is argu, y is actual result.

n=len(x)

return np.square(y-ax-b).sum()/n

優化函式則進行使損失函式,即方差最小的方向進行搜尋

a=a-theta(∂j/∂a)

b=b-theta*(∂j/∂b)

這裡的解釋就是,江蘇小學五年級輔導對影響因素a或b求損失函式j的偏導,如果損失函式隨著a或b增大而增大,我們就需要反方向搜尋,使得損失函式變小。

對於偏導的求取則看的別人的推導公式

theta為搜尋步長,影響速度和精度(我猜的,實際沒有驗證)

def optimize(a,b,x,y):

theta = 1e-1 # settle the step as 0.1

n=len(x)

y_hat = model(a,b,x)

# compute forecast values

da = ((y_hat-y)x).sum()/n

db = (y_hat-y).sum()/n

a = a - thetada

b = b - theta*db

return a, b

使用sklearn庫,可以使用現成的線性回歸模型

import numpy as np

from sklearn.linear_model import linearregression

import matplotlib.pyplot as plt

x = [1,2,4,5,6,6,7,9]

x = np.reshape(x,newshape=(8,1))

y = [10,9,9,9,7,5,3,1]

y = np.reshape(y,newshape=(8,1))

lr = linearregression()

lr.fit(x,y)

lr.score(x,y)

y_hat = lr.predict(x)

plt.scatter(x,y)

plt.plot(x, y_hat)

plt.show()

機器學習 一元線性回歸演算法

線性回歸 線性回歸擬合原理 fit方法 ridge回歸 損失函式 l2 lasso回歸 損失函式 l1 懲罰項係數alpha高,菱形面積小,alpha低,菱形面積大 elastic net 損失函式 l1 l2 舉例 lasso回歸是隨機梯度下降 l1,此處選擇懲罰項係數為0.15 與 之對比的sg...

機器學習之一元線性回歸(python實現)

1.確定假設函式 如 y 2x 7 其中,x,y 是一組資料,設共有m個 2.誤差cost 用平方誤差代價函式 3.減小誤差 用梯度下降 1.初始化資料 x y 樣本 learning rate 學習率 迴圈次數loopnum 梯度下降次數 2.梯度下降 迴圈 迴圈loopnum次 1 算偏導 需要...

機器學習(四)一元線性回歸

h x 0 1 xh theta x theta 0 theta 1x h x 0 1 x這個方程對於的影象是一條直線,稱為回歸線。其中 1 theta 1 1 為回歸線的斜率,0 theta 0 0 為回歸線的截距 j 0,1 1 2m i 1m yi h xi 2j theta 0,theta ...