機器學習第三天:線性多元迴歸
文章目錄
多元線性迴歸基本概念
與簡單線性迴歸相比,多元線性迴歸不過是多了幾個自變量x。
上篇所列的幾個方程更改如下:
多元線性迴歸模型:
y = β0 + β1x1 + β2x2 + … + βn*xn + E
多元迴歸方程:
E(y) = β0 + β1x1 + β2x2 + … + βn*xn
估計多元迴歸方程:
y_hat = b0 + b1x1 + b2x2 + … + bn*xn
利用一個樣本集計算出多元迴歸方程中β0,β1等值的估計值b0,b1等,得到估計方程。
利用樣本計算出方程b0,b1等參數的方法原則依然還是利用求和的公式。
具體實現步驟
第一步: 數據預處理
導入庫
import pandas as pd
import numpy as np
導入數據集
dataset = pd.read_csv(r'D:\data\50_Startups.csv') #搞清楚相對路徑和絕對路徑
X = dataset.iloc[ : , :-1].values
Y = dataset.iloc[ : , 4 ].values
print(X[:10])
print(Y)
[[165349.2 136897.8 471784.1 'New York']
[162597.7 151377.59 443898.53 'California']
[153441.51 101145.55 407934.54 'Florida']
[144372.41 118671.85 383199.62 'New York']
[142107.34 91391.77 366168.42 'Florida']
[131876.9 99814.71 362861.36 'New York']
[134615.46 147198.87 127716.82 'California']
[130298.13 145530.06 323876.68 'Florida']
[120542.52 148718.95 311613.29 'New York']
[123334.88 108679.17 304981.62 'California']]
[192261.83 191792.06 191050.39 182901.99 166187.94 156991.12 156122.51
155752.6 152211.77 149759.96 146121.95 144259.4 141585.52 134307.35
132602.65 129917.04 126992.93 125370.37 124266.9 122776.86 118474.03
111313.02 110352.25 108733.99 108552.04 107404.34 105733.54 105008.31
103282.38 101004.64 99937.59 97483.56 97427.84 96778.92 96712.8
96479.51 90708.19 89949.14 81229.06 81005.76 78239.91 77798.83
71498.49 69758.98 65200.33 64926.08 49490.75 42559.73 35673.41
14681.4 ]
將類別數據數字化
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder = LabelEncoder()
X[: , 3] = labelencoder.fit_transform(X[ : , 3])
print("labelencoder:")
print(X[:10])
onehotencoder = OneHotEncoder(categorical_features = [3])
X = onehotencoder.fit_transform(X).toarray()
print("onehot:")
print(X[:10])
labelencoder:
[[165349.2 136897.8 471784.1 2]
[162597.7 151377.59 443898.53 0]
[153441.51 101145.55 407934.54 1]
[144372.41 118671.85 383199.62 2]
[142107.34 91391.77 366168.42 1]
[131876.9 99814.71 362861.36 2]
[134615.46 147198.87 127716.82 0]
[130298.13 145530.06 323876.68 1]
[120542.52 148718.95 311613.29 2]
[123334.88 108679.17 304981.62 0]]
D:\an\lib\site-packages\sklearn\preprocessing\_encoders.py:415: FutureWarning: The handling of integer data will change in version 0.22. Currently, the categories are determined based on the range [0, max(values)], while in the future they will be determined based on the unique values.
If you want the future behaviour and silence this warning, you can specify "categories='auto'".
In case you used a LabelEncoder before this OneHotEncoder to convert the categories to integers, then you can now use the OneHotEncoder directly.
warnings.warn(msg, FutureWarning)
D:\an\lib\site-packages\sklearn\preprocessing\_encoders.py:451: DeprecationWarning: The 'categorical_features' keyword is deprecated in version 0.20 and will be removed in 0.22. You can use the ColumnTransformer instead.
"use the ColumnTransformer instead.", DeprecationWarning)
onehot:
[[0.0000000e+00 0.0000000e+00 1.0000000e+00 1.6534920e+05 1.3689780e+05
4.7178410e+05]
[1.0000000e+00 0.0000000e+00 0.0000000e+00 1.6259770e+05 1.5137759e+05
4.4389853e+05]
[0.0000000e+00 1.0000000e+00 0.0000000e+00 1.5344151e+05 1.0114555e+05
4.0793454e+05]
[0.0000000e+00 0.0000000e+00 1.0000000e+00 1.4437241e+05 1.1867185e+05
3.8319962e+05]
[0.0000000e+00 1.0000000e+00 0.0000000e+00 1.4210734e+05 9.1391770e+04
3.6616842e+05]
[0.0000000e+00 0.0000000e+00 1.0000000e+00 1.3187690e+05 9.9814710e+04
3.6286136e+05]
[1.0000000e+00 0.0000000e+00 0.0000000e+00 1.3461546e+05 1.4719887e+05
1.2771682e+05]
[0.0000000e+00 1.0000000e+00 0.0000000e+00 1.3029813e+05 1.4553006e+05
3.2387668e+05]
[0.0000000e+00 0.0000000e+00 1.0000000e+00 1.2054252e+05 1.4871895e+05
3.1161329e+05]
[1.0000000e+00 0.0000000e+00 0.0000000e+00 1.2333488e+05 1.0867917e+05
3.0498162e+05]]
躲避虛擬變量陷阱
在迴歸預測中我們需要所有的數據都是numeric的,但是會有一些非numeric的數據,比如國家,省,部門,性別。這時候我們需要設置虛擬變量(Dummy variable)。做法是將此變量中的每一個值,衍生成爲新的變量,是設爲1,否設爲0.舉個例子,“性別”這個變量,我們可以虛擬出“男”和”女”兩虛擬變量,男性的話“男”值爲1,”女”值爲0;女性的話“男”值爲0,”女”值爲1。
但是要注意,這時候虛擬變量陷阱就出現了。就拿性別來說,其實一個虛擬變量就夠了,比如 1 的時候是“男”, 0 的時候是”非男”,即爲女。如果設置兩個虛擬變量“男”和“女”,語義上來說沒有問題,可以理解,但是在迴歸預測中會多出一個變量,多出的這個變量將會對迴歸預測結果產生影響。一般來說,如果虛擬變量要比實際變量的種類少一個。
在多重線性迴歸中,變量不是越多越好,而是選擇適合的變量。這樣纔會對結果準確預測。如果category類的特徵都放進去,擬合的時候,所有權重的計算,都可以有兩種方法實現,一種是提高某個category的w,一種是降低其他category的w,這兩種效果是等效的,也就是發生了共線性,虛擬變量係數相加和爲1,出現完全共線陷阱
X1 = X[: , 1:] #躲避虛擬陷阱
拆分數據集爲訓練集和測試集
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)
X1_train, X1_test, Y1_train, Y1_test = train_test_split(X1, Y, test_size = 0.2, random_state = 0)
print(X_test)
print(Y_test)
print(X1_test)
print(Y1_test)
[[0.0000000e+00 1.0000000e+00 0.0000000e+00 6.6051520e+04 1.8264556e+05
1.1814820e+05]
[1.0000000e+00 0.0000000e+00 0.0000000e+00 1.0067196e+05 9.1790610e+04
2.4974455e+05]
[0.0000000e+00 1.0000000e+00 0.0000000e+00 1.0191308e+05 1.1059411e+05
2.2916095e+05]
[0.0000000e+00 1.0000000e+00 0.0000000e+00 2.7892920e+04 8.4710770e+04
1.6447071e+05]
[0.0000000e+00 1.0000000e+00 0.0000000e+00 1.5344151e+05 1.0114555e+05
4.0793454e+05]
[0.0000000e+00 0.0000000e+00 1.0000000e+00 7.2107600e+04 1.2786455e+05
3.5318381e+05]
[0.0000000e+00 0.0000000e+00 1.0000000e+00 2.0229590e+04 6.5947930e+04
1.8526510e+05]
[0.0000000e+00 0.0000000e+00 1.0000000e+00 6.1136380e+04 1.5270192e+05
8.8218230e+04]
[0.0000000e+00 1.0000000e+00 0.0000000e+00 7.3994560e+04 1.2278275e+05
3.0331926e+05]
[0.0000000e+00 1.0000000e+00 0.0000000e+00 1.4210734e+05 9.1391770e+04
3.6616842e+05]]
[103282.38 144259.4 146121.95 77798.83 191050.39 105008.31 81229.06
97483.56 110352.25 166187.94]
[[1.0000000e+00 0.0000000e+00 6.6051520e+04 1.8264556e+05 1.1814820e+05]
[0.0000000e+00 0.0000000e+00 1.0067196e+05 9.1790610e+04 2.4974455e+05]
[1.0000000e+00 0.0000000e+00 1.0191308e+05 1.1059411e+05 2.2916095e+05]
[1.0000000e+00 0.0000000e+00 2.7892920e+04 8.4710770e+04 1.6447071e+05]
[1.0000000e+00 0.0000000e+00 1.5344151e+05 1.0114555e+05 4.0793454e+05]
[0.0000000e+00 1.0000000e+00 7.2107600e+04 1.2786455e+05 3.5318381e+05]
[0.0000000e+00 1.0000000e+00 2.0229590e+04 6.5947930e+04 1.8526510e+05]
[0.0000000e+00 1.0000000e+00 6.1136380e+04 1.5270192e+05 8.8218230e+04]
[1.0000000e+00 0.0000000e+00 7.3994560e+04 1.2278275e+05 3.0331926e+05]
[1.0000000e+00 0.0000000e+00 1.4210734e+05 9.1391770e+04 3.6616842e+05]]
[103282.38 144259.4 146121.95 77798.83 191050.39 105008.31 81229.06
97483.56 110352.25 166187.94]
在訓練集上訓練多元線性迴歸模型
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)
regressor1 = LinearRegression()
regressor1.fit(X1_train, Y1_train)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)
在測試集上預測結果
y_pred = regressor.predict(X_test)
y1_pred = regressor1.predict(X1_test)
print(y_pred)
print(y1_pred)
[103015.20159796 132582.27760815 132447.73845173 71976.09851258
178537.48221051 116161.24230163 67851.69209676 98791.73374689
113969.43533011 167921.06569547]
[103015.20159795 132582.27760817 132447.73845176 71976.09851257
178537.48221058 116161.24230165 67851.69209675 98791.73374686
113969.43533013 167921.06569553]
知識點詳解
簡單線性迴歸:影響Y的因素唯一,只有一個。
多元線性迴歸:影響Y的因數不唯一,有多個。
與一元線性迴歸一樣,多元線性迴歸自然是一個迴歸問題。
一元線性迴歸方程:Y=aX+b。
多元線性迴歸是:Y=aX1+bX2+cX3+…+nXn。
相當於我們高中學的一元一次方程,變成了n元一次方程。因爲y還是那個y。只是自變量增加了。
在實際的機器學習的應用任務中,特徵有時候並不總是連續值,有可能是一些分類值,如性別可分爲“male”和“female”。在機器學習任務中,對於這樣的特徵,通常我們需要對其進行特徵數字化,如下面的例子:
有如下三個特徵屬性:
性別:[“male”,“female”]
地區:[“Europe”,“US”,“Asia”]
瀏覽器:[“Firefox”,“Chrome”,“Safari”,“Internet Explorer”]
通過LabelEncoder將其數字化:
性別:[0,1]
地區:[0,1,2]
瀏覽器:[0,1,2,3]
再用OneHotEncoder進行編碼:
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder()
enc.fit([[0, 0, 3],
[1, 1, 0],
[0, 2, 1],
[1, 0, 2]])
“”"
如果不加 toarray() 的話,輸出的是稀疏的存儲格式,即索引加值的形式,
也可以通過參數指定 sparse = False 來達到同樣的效果
“”"
ans = enc.transform([[0, 1, 3]]).toarray()
print(ans) # 輸出 [[ 1. 0. 0. 1. 0. 0. 0. 0. 1.]]
解釋:對於輸入數組,這依舊是把每一行當作一個樣本,每一列當作一個特徵。
我們先來看第一個特徵,即第一列 [0,1,0,1],也就是說它有兩個取值 0 或者 1,那麼 one-hot 就會使用兩位來表示這個特徵,[1,0] 表示 0, [0,1] 表示 1,在上例輸出結果中的前兩位 [1,0…] 也就是表示該特徵爲 0。
第二個特徵,第二列 [0,1,2,0],它有三種值,那麼 one-hot 就會使用三位來表示這個特徵,[1,0,0] 表示 0, [0,1,0] 表示 1,[0,0,1] 表示 2,在上例輸出結果中的第三位到第六位 […0,1,0,0…] 也就是表示該特徵爲 1。
第二個特徵,第三列 [3,0,1,2],它有四種值,那麼 one-hot 就會使用四位來表示這個特徵,[1,0,0,0] 表示 0, [0,1,0,0] 表示 1,[0,0,1,0] 表示 2,[0,0,0,1] 表示 3,在上例輸出結果中的最後四位 […0,0,0,1] 也就是表示該特徵爲 3
可以簡單理解爲“male”“US”“Safari”經過LabelEncoder與OneHotEncoder的編碼就變成了:[[1. 0. 0. 1. 0. 0. 0. 0. 1.]]
更多OneHot編碼知識可前往:scikit-learn 中 OneHotEncoder 解析
toarray():將列表轉化爲數組
Python原生沒有數組的概念,這點不同於Java之類的面嚮對象語言。Python中原生的列表使用起來很像數組,但是兩者有本質的區別
列表與數組的最本質的區別:列表中的所有元素的內存地址可以不是連續的,而數組是連續的。
更詳細的解釋:Python中列表與數組的區別
虛擬變量陷阱是指兩個以上(包括兩個)變量之間高度相關的情形。簡而言之,就是存在一個能被其他變量預測出的變量,舉一個存在重複類別(變量)的直觀例子:假使我們捨棄男性類別,那麼該類別也可以通過女性類別來定義(女性值爲0時,表示男性,爲1時,表示女性),反之亦然。
虛擬變量陷阱這裏就簡單瞭解,後面再深入討論。
言。Python中原生的列表使用起來很像數組,但是兩者有本質的區別
列表與數組的最本質的區別:列表中的所有元素的內存地址可以不是連續的,而數組是連續的。
更詳細的解釋:Python中列表與數組的區別
虛擬變量陷阱是指兩個以上(包括兩個)變量之間高度相關的情形。簡而言之,就是存在一個能被其他變量預測出的變量,舉一個存在重複類別(變量)的直觀例子:假使我們捨棄男性類別,那麼該類別也可以通過女性類別來定義(女性值爲0時,表示男性,爲1時,表示女性),反之亦然。
虛擬變量陷阱這裏就簡單瞭解,後面再深入討論。