機器學習 線性回歸

2021-10-05 05:57:00 字數 3428 閱讀 3258

線性回歸是非線性回歸、廣義線性回歸的基礎,因此在本系列的機器學習內容開始之前先對線性回歸進行深入學習,後續逐步展開樸素貝葉斯、em演算法、條件隨機場、svm共4部分的內容學習。

常用的損失函式包括:0-1損失函式、平方損失函式、絕對損失函式、對數損失函式等;常用的代價函式包括均方誤差、均方根誤差、平均絕對誤差等。

•損失函式(loss function):度量單樣本**的錯誤程度,損失函式值越小,模型就越好。

•代價函式(cost function):度量全部樣本集的平均誤差。

•目標函式(object function):代價函式和正則化函式,最終要優化的函式。

問題:1、首先嘗試呼叫sklearn的線性回歸函式進行訓練; sklearn.linear_model.linearregression

2、用最小二乘法的矩陣求解法訓練資料;

3、用梯度下降法訓練資料。

#生成隨機數

import numpy as np

np.random.seed(

1234

)x = np.random.rand(,3

)#構建對映關係,模擬真實的資料待**值,對映關係為y = 4.2 + 5.7*x1 + 10.8*x2,可自行設定值進行嘗試

y = x.dot(np.array(

[4.2

,5.7

,10.8])

)

呼叫sklearn線性回歸模型

import numpy as np

from sklearn.linear_model import linearregression

import matplotlib.pyplot as plt

%matplotlib inline

# 呼叫模型

lr = linearregression(fit_intercept=

true

)# 訓練模型

lr.fit(x,y)

print

("估計的引數值為:%s"

%(lr.coef_)

)# 計算r平方

print

('r2:%s'

%(lr.score(x,y)))

# 任意設定變數,**目標值

x_test = np.array([2

,4,5

]).reshape(1,

-1)y_hat = lr.predict(x_test)

print

("**值為: %s"

%(y_hat)

)

估計的引數值為:[ 4.2 5.7 10.8]

r2:1.0

**值為: [85.2]

(1)最小二乘法的矩陣求解

class

lr_ls()

:def

__init__

(self)

: self.w =

none

deffit

(self, x, y)

:# .inv(最小二乘法矩陣求解

self.w = np.linalgx.inv(x.t.dot(x)

).dot(x.t)

.dot(y)

defpredict

(self,x)

: y_pred = x.dot(self.w)

return y_pred

if __name__ ==

"__main__"

: lr_ls = lr_ls(

) lr_ls.fit(x,y)

print

("估計的引數值:%s"

%(lr_ls.w)

) x_test = np.array([2

,4,5

]).reshape(1,

-1)print

("**值為: %s"

%(lr_ls.predict(x_test)

))

(2)梯度下降法

class

lr_gd()

:def

__init__

(self)

: self.w =

none

deffit

(self,x,y,alpha=

0.02

,loss =1e-

10):# 設定步長為0.002,判斷是否收斂的條件為1e-10

y = y.reshape(-1

,1)#重塑y值的維度以便矩陣運算

[m,d]

= np.shape(x)

#自變數的維度

self.w = np.zeros(

(d))

#將引數的初始值定為0

tol =

1e5while tol > loss:

h_f = x.dot(self.w)

.reshape(-1

,1) theta = self.w + alpha*np.mean(x*

(y - h_f)

,axis=0)

#計算迭代的引數值

tol = np.

sum(np.

abs(theta - self.w)

) self.w = theta

defpredict

(self, x)

:# 用已經擬合的引數值**新自變數

y_pred = x.dot(self.w)

return y_pred

if __name__ ==

"__main__"

: lr_gd = lr_gd(

) lr_gd.fit(x,y)

print

("估計的引數值為:%s"

%(lr_gd.w)

) x_test = np.array([2

,4,5

]).reshape(1,

-1)print

("**值為:%s"

%(lr_gd.predict(x_test)

))

梯度下降法和最小二乘法結果一致。

機器學習 線性回歸

可以說基本上是機器學習中最簡單的模型了,但是實際上其地位很重要 計算簡單 效果不錯,在很多其他演算法中也可以看到用lr作為一部分 先來看乙個小例子,給乙個 線性回歸是什麼 的概念。圖來自 2 假設有乙個房屋銷售的資料如下 面積 m 2 銷售價錢 萬元 123 250 150 320 87 160 1...

機器學習(線性回歸)

在機器學習中,回歸 分類和標註共同構成了監督學習技術。監督學習 supervised learning 是機器學習在工業界應用最廣的乙個領域分支。在學術界中也是研究最多的領域之一。大家都知道的資料探勘十大經典演算法中,監督學習技術佔據6席。方法 自變數 特徵 因變數 結果 關係 回歸演算法是試圖採用...

機器學習 線性回歸

line fitter linearregression 建立模型 line fitter.fit temperature,sales 傳入引數 sales predict line fitter.predict temperature 模型 直線 直線上會有loss 計算loss時 要使用平方距離...