初始線性回歸 - 正規(guī)方程 - 梯度下降法 - 嶺回歸

一、初始線性回歸:

1、線性回歸的定義:
線性回歸(Linear regression)是利用回歸方程(函數(shù))一個或多個自變量(特征值)和因變量(目標(biāo)值)之間關(guān)系進(jìn)行建模的一種分析方式。
2、通用公式
h(w) = w1x1 + w2x2 +w3x3 ... + b = (wτ)x + b

通用公式.png

其中:w,x可以理解為矩陣:

image.png

3、線性回歸的分類: 線性關(guān)系、非線性關(guān)系。

4、線性回歸API:
sklearn.linear_model.LinearRegression()

  • LinearRegression.coef_: 線性回歸系數(shù)。

5、代碼演示??:根據(jù)學(xué)生的平時成績、期末成績預(yù)測學(xué)生的最終成績。

# coding:utf-8

from sklearn.linear_model import LinearRegression

# 1.獲取數(shù)據(jù)
x = [[80, 86],
     [82, 80],
     [85, 78],
     [90, 90],
     [86, 82],
     [82, 90],
     [78, 80],
     [92, 94]]

y = [84.2, 80.6, 80.1, 90, 83.2, 87.6, 79.4, 93.4]

# 2.模型訓(xùn)練
# 2.1 實(shí)例化一個估計(jì)器
estimator = LinearRegression()

# 2.2 使用fit方法進(jìn)行訓(xùn)練
estimator.fit(x, y)

# 打印對應(yīng)的系數(shù):
print("線性回歸的系數(shù)是:\n", estimator.coef_)

# 打印的預(yù)測結(jié)果是:
print("輸出預(yù)測結(jié)果:\n", estimator.predict([[100, 80]]))

6、運(yùn)行結(jié)果:

運(yùn)行結(jié)果:.png

二、導(dǎo)數(shù)-求導(dǎo):

1、常見函數(shù)的導(dǎo)數(shù):

常見函數(shù)的導(dǎo)數(shù):.png

2、導(dǎo)數(shù)的四則運(yùn)算:

導(dǎo)數(shù)的四則運(yùn)算.png

3、矩陣(向量)求導(dǎo):

矩陣(向量)求導(dǎo).png

三、線性回歸的損失和優(yōu)化:

1、損失函數(shù)公式:

損失函數(shù)公式.png

其中:
(1)yi為第i個訓(xùn)練樣本的真實(shí)值。
(2)h(xi)為第i個訓(xùn)練樣本特征值組合預(yù)測函數(shù)。
(3)又稱最小二乘法。
那么,如何減少這個損失,使我們預(yù)測的更加準(zhǔn)確些?既然存在這個損失,我們一直說機(jī)器學(xué)習(xí)有自動學(xué)習(xí)的功能,在線性回歸這里是能夠體現(xiàn)的。這里可以通過一些優(yōu)化方法去優(yōu)化(其實(shí)是數(shù)學(xué)當(dāng)中的求導(dǎo)功能)回歸的總損失!

2、正規(guī)方程:利用矩陣的逆,轉(zhuǎn)置進(jìn)行一步求解,只適合樣本和特征比較少的情況。

2.1、代碼示范??:

# coding:utf-8

"""
# 1.獲取數(shù)據(jù)
# 2.數(shù)據(jù)基本處理
# 2.1 分割數(shù)據(jù)
# 3.特征工程-標(biāo)準(zhǔn)化
# 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
# 5.模型評估
"""

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.metrics import mean_squared_error


def linear_model1():
    """
    線性回歸:正規(guī)方程
    :return:
    """

    # 1.獲取數(shù)據(jù)
    boston = load_boston()
    print(boston)

    # 2.數(shù)據(jù)基本處理
    # 2.1 分割數(shù)據(jù)
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2)

    # 3.特征工程-標(biāo)準(zhǔn)化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)

    # 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
    estimator = LinearRegression()
    estimator.fit(x_train, y_train)

    print("這個模型的偏置是:\n", estimator.intercept_)
    print("這個模型的系數(shù)是:\n", estimator.coef_)

    # 5.模型評估
    # 5.1 預(yù)測值
    y_pre = estimator.predict(x_test)
    print("預(yù)測值是:\n", y_pre)

    # 5.2 均方誤差
    ret = mean_squared_error(y_test, y_pre)
    print("均方誤差:\n", ret)


linear_model1()

2.2、運(yùn)行結(jié)果:

image.png

3、梯度下降(Gradient Descent):

3.1、基本思想:
梯度下降法可以類比為一個下山的過程
假設(shè)這樣一個場景:一個人被困在山上,需要從山上下來(i.e.找到山的最低點(diǎn),也就是山谷。但此時山上的濃霧很大,導(dǎo)致可視度很低)。因此,下山的路徑就無法確定,以他當(dāng)前的位置為基準(zhǔn)尋找這個位置最陡峭的地方,然后朝著山的高度下降的地方走,然后沒走一段距離,都反復(fù)采用同一個方法,最后就能成功的抵達(dá)山谷。

梯度下降法基本思想.png

梯度下降的基本過程就和下山的場景很類似:
首先,我們有一個可微分的函數(shù),這個函數(shù)就代表著一座山
我們的目標(biāo)就是找到這個函數(shù)的最小值,也就是山底。

根據(jù)之前的場景假設(shè),最快的下山方式就是找到當(dāng)前位置最陡峭的方向,然后沿著此方向向下走,對應(yīng)到函數(shù)中,就是找到給定點(diǎn)的梯度,然后朝著梯度相反的方向,就能讓函數(shù)值下降的最快!因?yàn)樘荻鹊姆较蚓褪呛瘮?shù)值變化最快的方向。所以,我們重復(fù)利用這個方法,反復(fù)求取梯度,最后就能到達(dá)局部最小值,這就類似于我們下山的過程。而求取梯度就確定了最陡峭的方向,也就是場景中測量方向的手段。

3.2、梯度的概念:
梯度是微積分中一個很重要的概念。
在單變量的函數(shù)中,梯度其實(shí)就是函數(shù)的微分,代表著函數(shù)在某個給定點(diǎn)的切線的斜率;
在多變量函數(shù)中,梯度是一個向量,向量有方向,梯度的方向就指出了函數(shù)在給定點(diǎn)的上升最快的方向;
這也就說明了為什么我們需要千方百計(jì)地求取梯度!我們需要到達(dá)山底,就需要在每一步觀測到此時最陡峭的地方,梯度就恰好告訴我們這個方向。梯度的方向是函數(shù)在給定點(diǎn)上升最快的方向,那么梯度的反方向就是函數(shù)在給定點(diǎn)下降最快的方向,這正是我們所需要的。所以我們只要沿著梯度的方向一直走,就能走到局部的最低點(diǎn)。

3.3、梯度下降舉例:
(1)單變量函數(shù)的梯度下降:
我們假設(shè)有一個單變量的函數(shù)J(θ) = θ^2 (其中;θ^2指的是θ的平方 )

函數(shù)的微分:J`(θ) = 2θ。

初始化,起點(diǎn)為: θ^0 = 1

學(xué)習(xí)率: α = 0.4

我們開始進(jìn)行梯度下降的迭代計(jì)算過程:

θ^0 = 1

θ^1 = θ^0 - α * J`(θ^0) = 1 - 0.4 * 2 = 0.2

θ^2 = θ^1 - α * J`(θ^1) = 0.04

θ^3 = θ^2 - α * J`(θ^2) = 0.008

θ^4 = θ^13- α * J`(θ^3) = 0.0016

如圖,經(jīng)過四次的運(yùn)算,也就是走了四部,基本就抵達(dá)了函數(shù)的最低點(diǎn)山底了:

梯度下降過程.png

(2)多變量函數(shù)的的梯度下降:
假設(shè)有一個目標(biāo)函數(shù):J(θ) = θ1^2 + θ2^2
現(xiàn)在要通過梯度下降法計(jì)算這個函數(shù)的最小值,我們通過觀察不難發(fā)現(xiàn)其實(shí)就是(0,0)點(diǎn)。但是接下來,我們從梯度下降算法開始一步步計(jì)算到這個最小值!我們假設(shè):
初始的起點(diǎn)為:θ^0 = (1, 3)

初始的學(xué)習(xí)率為:α = 0.1

函數(shù)的梯度為:▽:J(θ) =<2θ1, 2θ2)>

進(jìn)行多次迭代:

θ^0 = (1, 3)

θ^1 = θ^0 - α▽J(θ) = (1, 3) - 0.1(2, 6) = (0.8, 2.4)

θ^2 = θ^1 - α▽J(θ) = (0.8, 2.4) - 0.1(1.6, 4.8) = (0.64, 1.92)

θ^3 = θ^2 - α▽J(θ) = (0.512, 1.536)

θ^4 = θ^3 - α▽J(θ) = (0.4096, 1.2288000000000001)
.
.
.
θ^10 = (0.10737418240000003, 0.32212254720000005)
.
.
.
θ^50 = (1.1417981541647683e-05, 3.425394462494306e-05)
.
.
.
θ^100 = (1.6296287810675902e-10, 4.888886343202771e-10)

我們發(fā)現(xiàn),已經(jīng)基本靠近函數(shù)的最小值點(diǎn):

多變量函數(shù)的梯度下降.png

3.4、梯度下降公式:

梯度下降公式.png

(1)α 在梯度下降算法中被稱作 學(xué)習(xí)率或者步長,控制每一步走的距離,控制步長很重要,不能太小,也不能太大。

(2)α后面的部分決定了梯度下降的方向。

(3)特點(diǎn):

  • 初始點(diǎn)不同,獲得的最小值也不同,因此梯度下降求得的只是局部最小值;
  • 越接近最小值時,下降速度越慢;

(4)梯度下降法沒辦法保證走到最小值,可能只是極小值:

梯度下降法可能走到的值.png

3.5、常見的梯度下降法:
(1)、全梯度下降算法(Full gradient descent):使用所有樣本,整個數(shù)據(jù)集。
(2)、隨機(jī)梯度下降算法(Stochastic gradient descent),
(3)、小批量梯度下降算法(Mini-batch gradient descent),
(4)、隨機(jī)平均梯度下降算法(Stochastic average gradient descent)。
它們都是為了正確地調(diào)節(jié)權(quán)重向量沒通過為每個權(quán)重計(jì)算一個梯度,從而更新權(quán)值,是目標(biāo)函數(shù)盡可能最小化。其差別在于樣本的使用方式不同。

3.6、梯度下降法代碼示范??:

# coding:utf-8

"""
# 1.獲取數(shù)據(jù)
# 2.數(shù)據(jù)基本處理
# 2.1 分割數(shù)據(jù)
# 3.特征工程-標(biāo)準(zhǔn)化
# 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
# 5.模型評估
"""

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.metrics import mean_squared_error


def linear_model1():
    """
    線性回歸:正規(guī)方程
    :return:
    """

    # 1.獲取數(shù)據(jù)
    boston = load_boston()
    print(boston)

    # 2.數(shù)據(jù)基本處理
    # 2.1 分割數(shù)據(jù)
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2)

    # 3.特征工程-標(biāo)準(zhǔn)化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)

    # 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
    estimator = LinearRegression()
    estimator.fit(x_train, y_train)

    print("這個模型的偏置是:\n", estimator.intercept_)
    print("這個模型的系數(shù)是:\n", estimator.coef_)

    # 5.模型評估
    # 5.1 預(yù)測值
    y_pre = estimator.predict(x_test)
    print("預(yù)測值是:\n", y_pre)

    # 5.2 均方誤差
    ret = mean_squared_error(y_test, y_pre)
    print("均方誤差:\n", ret)


def linear_model2():
    """
    線性回歸:梯度下降法
    :return:
    """

    # 1.獲取數(shù)據(jù)
    boston = load_boston()
    print(boston)

    # 2.數(shù)據(jù)基本處理
    # 2.1 分割數(shù)據(jù)
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2)

    # 3.特征工程-標(biāo)準(zhǔn)化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)

    # 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
    estimator = SGDRegressor(max_iter=1000)
    estimator.fit(x_train, y_train)

    print("這個模型的偏置是:\n", estimator.intercept_)
    print("這個模型的系數(shù)是:\n", estimator.coef_)

    # 5.模型評估
    # 5.1 預(yù)測值
    y_pre = estimator.predict(x_test)
    print("預(yù)測值是:\n", y_pre)

    # 5.2 均方誤差
    ret = mean_squared_error(y_test, y_pre)
    print("均方誤差:\n", ret)


# linear_model1()
linear_model2()

3.7、運(yùn)行結(jié)果:

梯度下降法運(yùn)行結(jié)果.png

四、線性回歸的改進(jìn) - 嶺回歸(Tikhonov regularization):

1、嶺回歸是線性回歸的正則化版本,即在原來的線性回歸的cost function懲罰函數(shù)中添加正則項(xiàng)(regularization term):

正則項(xiàng).png

以達(dá)到在你和數(shù)據(jù)的同時,使模型權(quán)重盡可能小的目的,嶺回歸代價函數(shù):

嶺回歸代價函數(shù).png

即:


嶺回歸代價函數(shù).png

2、嶺回歸API: sklearn.linear_model.Ridge(alpha=1.0,fit_intercept=True, normalize=False)

  • 具有l(wèi)2正則化的線性回歸
  • alpha:正則化力度,也叫 λ
    λ取值: 0~1 1~10
  • solver:會根據(jù)數(shù)據(jù)自動選擇優(yōu)化方法
    sag:如果數(shù)據(jù)集、特征都比較大,選擇該隨機(jī)梯度下降優(yōu)化
  • normalize:數(shù)據(jù)是否進(jìn)行標(biāo)準(zhǔn)化
    normalize=False:可以在fit之前調(diào)用preprocessing.StandardScaler標(biāo)準(zhǔn)化
    數(shù)據(jù)
    normalize=True:默認(rèn)對數(shù)據(jù)標(biāo)準(zhǔn)化進(jìn)行了封裝,會自動進(jìn)行數(shù)據(jù)標(biāo)準(zhǔn)化
  • Ridge.coef:回歸權(quán)重
  • Ridge.intercept: 回歸偏置
    注意:Ridge方法相當(dāng)于SGDRegressor(penalty='l2', loss="squared_loss"),只不過SGDRegressor實(shí)現(xiàn)了一個普通的隨機(jī)梯度下降學(xué)習(xí),推薦使用Ridge(實(shí)現(xiàn)了SAG)
  • sklearn.linear_model.RidgeCV(BaseRidgeCV, RegressorMixin)
    (1) 具有l(wèi)2正則化的線性回歸,可以進(jìn)行交叉驗(yàn)證
    (2)coef
    :回歸系數(shù)

3、正則化程度的變化對結(jié)果的影響:

正則化程度的變化對結(jié)果的影響.png
  • 正則化力度越大,權(quán)重系數(shù)會越小
  • 正則化力度越小,權(quán)重系數(shù)會越大

4、嶺回歸代碼演示??:

# coding:utf-8

"""
# 1.獲取數(shù)據(jù)
# 2.數(shù)據(jù)基本處理
# 2.1 分割數(shù)據(jù)
# 3.特征工程-標(biāo)準(zhǔn)化
# 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
# 5.模型評估
"""

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, SGDRegressor, RidgeCV, Ridge
from sklearn.metrics import mean_squared_error


def linear_model1():
    """
    線性回歸:正規(guī)方程
    :return:
    """

    # 1.獲取數(shù)據(jù)
    boston = load_boston()
    # print(boston)

    # 2.數(shù)據(jù)基本處理
    # 2.1 分割數(shù)據(jù)
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2)

    # 3.特征工程-標(biāo)準(zhǔn)化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)

    # 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
    estimator = LinearRegression()
    estimator.fit(x_train, y_train)

    print("這個模型的偏置是:\n", estimator.intercept_)
    print("這個模型的系數(shù)是:\n", estimator.coef_)

    # 5.模型評估
    # 5.1 預(yù)測值
    y_pre = estimator.predict(x_test)
    print("預(yù)測值是:\n", y_pre)

    # 5.2 均方誤差
    ret = mean_squared_error(y_test, y_pre)
    print("均方誤差:\n", ret)


def linear_model2():
    """
    線性回歸:梯度下降法
    :return:
    """

    # 1.獲取數(shù)據(jù)
    boston = load_boston()
    # print(boston)

    # 2.數(shù)據(jù)基本處理
    # 2.1 分割數(shù)據(jù)
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2)

    # 3.特征工程-標(biāo)準(zhǔn)化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)

    # 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
    estimator = SGDRegressor(max_iter=1000)
    estimator.fit(x_train, y_train)

    print("這個模型的偏置是:\n", estimator.intercept_)
    print("這個模型的系數(shù)是:\n", estimator.coef_)

    # 5.模型評估
    # 5.1 預(yù)測值
    y_pre = estimator.predict(x_test)
    print("預(yù)測值是:\n", y_pre)

    # 5.2 均方誤差
    ret = mean_squared_error(y_test, y_pre)
    print("均方誤差:\n", ret)


def linear_model3():
    """
    線性回歸:嶺回歸
    :return:None
    """

    # 1.獲取數(shù)據(jù)
    boston = load_boston()
    # print(boston)

    # 2.數(shù)據(jù)基本處理
    # 2.1 分割數(shù)據(jù)
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2)

    # 3.特征工程-標(biāo)準(zhǔn)化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)

    # 4.機(jī)器學(xué)習(xí)-模型訓(xùn)練-線性回歸
    # estimator = Ridge(alpha=1.0)
    estimator = RidgeCV(alphas=(0.001, 0.01, 0.1, 1, 10, 100))
    estimator.fit(x_train, y_train)

    print("嶺回歸這個模型的偏置是:\n", estimator.intercept_)
    print("嶺回歸這個模型的系數(shù)是:\n", estimator.coef_)

    # 5.模型評估
    # 5.1 預(yù)測值
    y_pre = estimator.predict(x_test)
    print("嶺回歸預(yù)測值是:\n", y_pre)

    # 5.2 均方誤差
    ret = mean_squared_error(y_test, y_pre)
    print("嶺回歸均方誤差:\n", ret)


if __name__ == '__main__':
    linear_model1()
    linear_model2()
    linear_model3()


5、嶺回歸代碼運(yùn)行結(jié)果:

嶺回歸代碼運(yùn)行結(jié)果.png

6、可以釋放之前注釋的代碼,并注釋掉多余部分,進(jìn)行多種方法運(yùn)行結(jié)果的簡單對比。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容