線性回歸與波士頓房?jī)r(jià)預(yù)測(cè)
一、實(shí)驗(yàn)?zāi)康?/h3>
- 掌握機(jī)器學(xué)習(xí)的基本概念
- 掌握線性回歸的實(shí)現(xiàn)過程
- 應(yīng)用LinearRegression實(shí)現(xiàn)回歸預(yù)測(cè)
- 知道回歸算法的評(píng)估標(biāo)準(zhǔn)及其公式
- 知道過擬合與欠擬合的原因以及解決方法
二、實(shí)驗(yàn)設(shè)備
- Jupter Notebook
三、實(shí)驗(yàn)內(nèi)容
人們?cè)谏钪薪?jīng)常遇到分類與預(yù)測(cè)的問題,目標(biāo)變量可能受多個(gè)因素影響,根據(jù)相關(guān)系數(shù)可以判斷影響因子的重要性。正如一個(gè)病人得某種病是多種因素影響造成的。
房子作為居住的場(chǎng)所,對(duì)每個(gè)人而言是不可或缺的。而房?jī)r(jià)的高低也是受多種因素的影響。房子所處的城市是一線還是二線,房子周邊的交通便利程度,房子附近是否存在醫(yī)院或者學(xué)校等,眾多因素都會(huì)影響房?jī)r(jià)。
“回歸”是由英國(guó)著名生物學(xué)家兼統(tǒng)計(jì)學(xué)家高爾頓(Francis Galton,1822~1911.生物學(xué)家達(dá)爾文的表弟)在研究人類遺傳問題時(shí)提出來的。19世紀(jì)高斯系統(tǒng)地提出最小二乘估計(jì),從而使回歸分析得到蓬勃發(fā)展。
波士頓房?jī)r(jià)數(shù)據(jù)源于美國(guó)某經(jīng)濟(jì)學(xué)雜志上,分析研究波士頓房?jī)r(jià)( Boston HousePrice)的數(shù)據(jù)集。數(shù)據(jù)集中的每一行數(shù)據(jù)都是對(duì)波士頓周邊或城鎮(zhèn)房?jī)r(jià)的情況描述,本實(shí)驗(yàn)以波士頓房?jī)r(jià)數(shù)據(jù)集為線性回歸案例數(shù)據(jù),進(jìn)行模型訓(xùn)練,預(yù)測(cè)波士頓房?jī)r(jià)。
3.1 了解數(shù)據(jù)
首先導(dǎo)入需要的包
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
from sklearn import preprocessing
加載波士頓房?jī)r(jià)的數(shù)據(jù)集
data = load_boston()
data_pd = pd.DataFrame(data.data,columns=data.feature_names)
data_pd['price'] = data.target
在拿到數(shù)據(jù)之后,先要查看數(shù)據(jù)的類型,是否有空值,數(shù)據(jù)的描述信息等等。
可以看到數(shù)據(jù)都是定量數(shù)據(jù)。
# 查看數(shù)據(jù)類型
data_pd.describe()
CRIM | ZN | INDUS | CHAS | NOX | RM | AGE | DIS | RAD | TAX | PTRATIO | B | LSTAT | price | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
count | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 | 506.000000 |
mean | 3.613524 | 11.363636 | 11.136779 | 0.069170 | 0.554695 | 6.284634 | 68.574901 | 3.795043 | 9.549407 | 408.237154 | 18.455534 | 356.674032 | 12.653063 | 22.532806 |
std | 8.601545 | 23.322453 | 6.860353 | 0.253994 | 0.115878 | 0.702617 | 28.148861 | 2.105710 | 8.707259 | 168.537116 | 2.164946 | 91.294864 | 7.141062 | 9.197104 |
min | 0.006320 | 0.000000 | 0.460000 | 0.000000 | 0.385000 | 3.561000 | 2.900000 | 1.129600 | 1.000000 | 187.000000 | 12.600000 | 0.320000 | 1.730000 | 5.000000 |
25% | 0.082045 | 0.000000 | 5.190000 | 0.000000 | 0.449000 | 5.885500 | 45.025000 | 2.100175 | 4.000000 | 279.000000 | 17.400000 | 375.377500 | 6.950000 | 17.025000 |
50% | 0.256510 | 0.000000 | 9.690000 | 0.000000 | 0.538000 | 6.208500 | 77.500000 | 3.207450 | 5.000000 | 330.000000 | 19.050000 | 391.440000 | 11.360000 | 21.200000 |
75% | 3.677083 | 12.500000 | 18.100000 | 0.000000 | 0.624000 | 6.623500 | 94.075000 | 5.188425 | 24.000000 | 666.000000 | 20.200000 | 396.225000 | 16.955000 | 25.000000 |
max | 88.976200 | 100.000000 | 27.740000 | 1.000000 | 0.871000 | 8.780000 | 100.000000 | 12.126500 | 24.000000 | 711.000000 | 22.000000 | 396.900000 | 37.970000 | 50.000000 |
接下來要查看數(shù)據(jù)是否存在空值,從結(jié)果來看數(shù)據(jù)不存在空值。
# 查看空缺值
data_pd.isnull().sum()
CRIM 0
ZN 0
INDUS 0
CHAS 0
NOX 0
RM 0
AGE 0
DIS 0
RAD 0
TAX 0
PTRATIO 0
B 0
LSTAT 0
price 0
dtype: int64
可以看出來數(shù)據(jù)集中沒有空缺值。
# 查看數(shù)據(jù)大小
data_pd.shape
(506, 14)
數(shù)據(jù)集有14列,506行
查看數(shù)據(jù)前5行,同時(shí)給出數(shù)據(jù)特征的含義
data_pd.head()
CRIM | ZN | INDUS | CHAS | NOX | RM | AGE | DIS | RAD | TAX | PTRATIO | B | LSTAT | price | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0.00632 | 18.0 | 2.31 | 0.0 | 0.538 | 6.575 | 65.2 | 4.0900 | 1.0 | 296.0 | 15.3 | 396.90 | 4.98 | 24.0 |
1 | 0.02731 | 0.0 | 7.07 | 0.0 | 0.469 | 6.421 | 78.9 | 4.9671 | 2.0 | 242.0 | 17.8 | 396.90 | 9.14 | 21.6 |
2 | 0.02729 | 0.0 | 7.07 | 0.0 | 0.469 | 7.185 | 61.1 | 4.9671 | 2.0 | 242.0 | 17.8 | 392.83 | 4.03 | 34.7 |
3 | 0.03237 | 0.0 | 2.18 | 0.0 | 0.458 | 6.998 | 45.8 | 6.0622 | 3.0 | 222.0 | 18.7 | 394.63 | 2.94 | 33.4 |
4 | 0.06905 | 0.0 | 2.18 | 0.0 | 0.458 | 7.147 | 54.2 | 6.0622 | 3.0 | 222.0 | 18.7 | 396.90 | 5.33 | 36.2 |
數(shù)據(jù)集變量說明下,方便大家理解數(shù)據(jù)集變量代表的意義。
- CRIM: 城鎮(zhèn)人均犯罪率
- ZN: 住宅用地所占比例
- INDUS: 城鎮(zhèn)中非住宅用地所占比例
- CHAS: 虛擬變量,用于回歸分析
- NOX: 環(huán)保指數(shù)
- RM: 每棟住宅的房間數(shù)
- AGE: 1940 年以前建成的自住單位的比例
- DIS: 距離 5 個(gè)波士頓的就業(yè)中心的加權(quán)距離
- RAD: 距離高速公路的便利指數(shù)
- TAX: 每一萬美元的不動(dòng)產(chǎn)稅率
- PTRATIO: 城鎮(zhèn)中的教師學(xué)生比例
- B: 城鎮(zhèn)中的黑人比例
- LSTAT: 地區(qū)中有多少房東屬于低收入人群
- price: 自住房屋房?jī)r(jià)中位數(shù)(也就是均價(jià))
3.2 分析數(shù)據(jù)
計(jì)算每一個(gè)特征和price的相關(guān)系數(shù)
data_pd.corr()['price']
CRIM -0.388305
ZN 0.360445
INDUS -0.483725
CHAS 0.175260
NOX -0.427321
RM 0.695360
AGE -0.376955
DIS 0.249929
RAD -0.381626
TAX -0.468536
PTRATIO -0.507787
B 0.333461
LSTAT -0.737663
price 1.000000
Name: price, dtype: float64
將相關(guān)系數(shù)絕對(duì)值大于0.5的特征畫圖顯示出來:
corr = data_pd.corr()
corr = corr['price']
corr[abs(corr)>0.5].sort_values().plot.bar()
<matplotlib.axes._subplots.AxesSubplot at 0x13d1990e5e0>
可以看出LSTAT、PTRATIO、RM三個(gè)特征的相關(guān)系數(shù)大于0.5,下面畫出三個(gè)特征關(guān)于price的散點(diǎn)圖。
(1)LSTAT和price的散點(diǎn)圖
data_pd.plot(kind="scatter",x="LSTAT",y="price")
<matplotlib.axes._subplots.AxesSubplot at 0x13d198bc3d0>
data_pd.plot(kind="scatter",x="PTRATIO",y="price")
<matplotlib.axes._subplots.AxesSubplot at 0x13d199dca60>
?
data_pd.plot(kind="scatter",x="RM",y="price")
<matplotlib.axes._subplots.AxesSubplot at 0x13d19a2f430>
可以看出三個(gè)特征和價(jià)格都有明顯的線性關(guān)系。
3.3 建立模型
(一)使用一個(gè)變量進(jìn)行預(yù)測(cè)
(1)使用LASTAT
做一元線性回歸
首先制作訓(xùn)練集和測(cè)試集
# 制作訓(xùn)練集和測(cè)試集的數(shù)據(jù)
feature_cols = ['LSTAT']
X = data_pd[feature_cols]
y = data_pd['price']
# 分割訓(xùn)練集和測(cè)試集
train_X,test_X,train_Y,test_Y = train_test_split(X,y)
y.describe()
count 506.000000
mean 22.532806
std 9.197104
min 5.000000
25% 17.025000
50% 21.200000
75% 25.000000
max 50.000000
Name: price, dtype: float64
# 加載模型
linreg = LinearRegression()
# 擬合數(shù)據(jù)
linreg.fit(train_X,train_Y)
print(linreg.intercept_)
# pair the feature names with the coefficients
b=list(zip(feature_cols, linreg.coef_))
b
63.81849572918555
[('PTRATIO', -2.2442477329043706)]
# 進(jìn)行預(yù)測(cè)
y_predict = linreg.predict(test_X)
# 計(jì)算均方根誤差
print("均方根誤差=",metrics.mean_squared_error(y_predict,test_Y))
均方根誤差= 74.6287048997467
畫圖
import seaborn as sns #seaborn就是在matplot的基礎(chǔ)上進(jìn)行了進(jìn)一步封裝
sns.lmplot(x='LSTAT', y='price', data=data_pd, aspect=1.5, scatter_kws={'alpha':0.2})
<seaborn.axisgrid.FacetGrid at 0x13d1b0f5a00>
(2)使用PTRATIO
做一元線性回歸
# 制作訓(xùn)練集和測(cè)試集的數(shù)據(jù)
feature_cols = ['PTRATIO']
X = data_pd[feature_cols]
y = data_pd['price']
# 分割訓(xùn)練集和測(cè)試集
train_X,test_X,train_Y,test_Y = train_test_split(X,y)
# 加載模型
linreg = LinearRegression()
# 擬合數(shù)據(jù)
linreg.fit(train_X,train_Y)
print(linreg.intercept_)
# pair the feature names with the coefficients
b=list(zip(feature_cols, linreg.coef_))
b
61.54376809966996
[('PTRATIO', -2.1175617470715635)]
# 進(jìn)行預(yù)測(cè)
y_predict = linreg.predict(test_X)
# 計(jì)算均方根誤差
print("均方根誤差=",metrics.mean_squared_error(y_predict,test_Y))
均方根誤差= 54.541969092283985
畫圖
import seaborn as sns #seaborn就是在matplot的基礎(chǔ)上進(jìn)行了進(jìn)一步封裝
sns.lmplot(x='PTRATIO', y='price', data=data_pd, aspect=1.5, scatter_kws={'alpha':0.2})
<seaborn.axisgrid.FacetGrid at 0x13d1b140490>
(3)使用RM
做一元線性回歸
# 制作訓(xùn)練集和測(cè)試集的數(shù)據(jù)
feature_cols = ['RM']
X = data_pd[feature_cols]
y = data_pd['price']
# 分割訓(xùn)練集和測(cè)試集
train_X,test_X,train_Y,test_Y = train_test_split(X,y)
# 加載模型
linreg = LinearRegression()
# 擬合數(shù)據(jù)
linreg.fit(train_X,train_Y)
print(linreg.intercept_)
# pair the feature names with the coefficients
b=list(zip(feature_cols, linreg.coef_))
b
-32.662292886508155
[('RM', 8.738014969584246)]
# 進(jìn)行預(yù)測(cè)
y_predict = linreg.predict(test_X)
# 計(jì)算均方根誤差
print("均方根誤差=",metrics.mean_squared_error(y_predict,test_Y))
均方根誤差= 51.81438126437724
畫圖
import seaborn as sns #seaborn就是在matplot的基礎(chǔ)上進(jìn)行了進(jìn)一步封裝
sns.lmplot(x='RM', y='price', data=data_pd, aspect=1.5, scatter_kws={'alpha':0.2})
<seaborn.axisgrid.FacetGrid at 0x13d1b1addc0>
?
根據(jù)均方根誤差進(jìn)行模型比較文章來源:http://www.zghlxwxcb.cn/news/detail-506318.html
答案:RM一元回歸分析的均方根誤差最小,所以該模型最好
(二)使用多元線性回歸分析進(jìn)行預(yù)測(cè)
使用LSTAT
,PTRATIO
,RM
做多元線性回歸分析
首先制作訓(xùn)練集和測(cè)試集
# 制作訓(xùn)練集和測(cè)試集的數(shù)據(jù)
feature_cols = ['LSTAT','PTRATIO','RM']
X = data_pd[feature_cols]
y = data_pd['price']
# 分割訓(xùn)練集和測(cè)試集
train_X,test_X,train_Y,test_Y = train_test_split(X,y)
# 加載模型
linreg = LinearRegression()
# 擬合數(shù)據(jù)
linreg.fit(train_X,train_Y)
print(linreg.intercept_)
# pair the feature names with the coefficients
b=list(zip(feature_cols, linreg.coef_))
b
24.145147504479777
[('LSTAT', -0.6077646658186993),
('PTRATIO', -0.9890097312795556),
('RM', 3.894020674969254)]
# 進(jìn)行預(yù)測(cè)
y_predict = linreg.predict(test_X)
# 計(jì)算均方根誤差
print("均方根誤差=",metrics.mean_squared_error(y_predict,test_Y))
均方根誤差= 22.06146178562167
畫圖比較
將訓(xùn)練好的測(cè)試集和原始測(cè)試集繪圖比較
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.sans-serif'] = 'SimHei'
fig = plt.figure(figsize=(10,6)) ##設(shè)定空白畫布,并制定大小
##用不同的顏色表示不同數(shù)據(jù)
plt.plot(range(test_Y.shape[0]),test_Y,color="blue", linewidth=1.5, linestyle="-")
plt.plot(range(test_Y.shape[0]),y_predict,color="red", linewidth=1.5, linestyle="-.")
plt.legend(['真實(shí)值','預(yù)測(cè)值'])
plt.show() ##顯示圖片
根據(jù)均方根誤差進(jìn)行模型比較
答案:多元線性回歸分析的均方根誤差最小,所以該模型最好文章來源地址http://www.zghlxwxcb.cn/news/detail-506318.html
文章目錄
序號(hào) | 文章目錄 | 直達(dá)鏈接 |
---|---|---|
實(shí)驗(yàn)一 | 語法、變量和數(shù)據(jù)類型 | https://want595.blog.csdn.net/article/details/131396590 |
實(shí)驗(yàn)二 | 函數(shù)調(diào)用 | https://want595.blog.csdn.net/article/details/131397066 |
實(shí)驗(yàn)三 | 布爾變量與條件語句 | https://want595.blog.csdn.net/article/details/131397310 |
實(shí)驗(yàn)四 | 列表 | https://want595.blog.csdn.net/article/details/131397482 |
實(shí)驗(yàn)五 | 循環(huán) | https://want595.blog.csdn.net/article/details/131397558 |
實(shí)驗(yàn)六 | 字符串與字典 | https://want595.blog.csdn.net/article/details/131397724 |
實(shí)驗(yàn)七 | 數(shù)據(jù)探索與數(shù)據(jù)預(yù)處理 | https://want595.blog.csdn.net/article/details/131474545 |
實(shí)驗(yàn)八 | 利用線形圖可視化股票的走勢(shì) | https://want595.blog.csdn.net/article/details/128612047 |
實(shí)驗(yàn)九 | 線性回歸與波士頓房?jī)r(jià)預(yù)測(cè) | https://want595.blog.csdn.net/article/details/131398054 |
到了這里,關(guān)于實(shí)驗(yàn) 09 線性回歸與波士頓房?jī)r(jià)預(yù)測(cè)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!