【python資料探勘課程】十八.線性迴歸及多項式迴歸分析四個案例分享

Eastmount發表於2017-11-26
這是《Python資料探勘課程》系列文章,也是我這學期大資料金融學院上課的部分內容。本文主要講述和分享線性迴歸作業中,學生們做得比較好的四個案例,經過我修改後供大家學習,內容包括:
    1.線性迴歸預測Pizza價格案例
    2.線性迴歸分析波士頓房價案例
    3.隨機資料集一元線性迴歸分析和三維迴歸分析案例
    4.Pizza資料集一元線性迴歸和多元線性迴歸分析

本篇文章為初始篇,基礎文章希望對你有所幫助,如果文章中存在錯誤或不足支援,還請海涵~自己真的太忙了,只能擠午休或深夜的時間學習新知識,但也得加油。


前文參考:
【Python資料探勘課程】一.安裝Python及爬蟲入門介紹
【Python資料探勘課程】二.Kmeans聚類資料分析及Anaconda介紹
【Python資料探勘課程】三.Kmeans聚類程式碼實現、作業及優化
【Python資料探勘課程】四.決策樹DTC資料分析及鳶尾資料集分析
【Python資料探勘課程】五.線性迴歸知識及預測糖尿病例項
【Python資料探勘課程】六.Numpy、Pandas和Matplotlib包基礎知識
【Python資料探勘課程】七.PCA降維操作及subplot子圖繪製
【Python資料探勘課程】八.關聯規則挖掘及Apriori實現購物推薦
【Python資料探勘課程】九.迴歸模型LinearRegression簡單分析氧化物資料
【python資料探勘課程】十.Pandas、Matplotlib、PCA繪圖實用程式碼補充
【python資料探勘課程】十一.Pandas、Matplotlib結合SQL語句視覺化分析
【python資料探勘課程】十二.Pandas、Matplotlib結合SQL語句對比圖分析
【python資料探勘課程】十三.WordCloud詞雲配置過程及詞頻分析
【python資料探勘課程】十四.Scipy呼叫curve_fit實現曲線擬合
【python資料探勘課程】十五.Matplotlib呼叫imshow()函式繪製熱圖
【python資料探勘課程】十六.邏輯迴歸LogisticRegression分析鳶尾花資料
【python資料探勘課程】十七.社交網路Networkx庫分析人物關係(初識篇)



一. 線性迴歸預測Pizza價格案例


1.資料集介紹

本章主要使用線性迴歸預測Pizza的價格,由於直徑大小不同的Pizza,其價格也是不同的。這是一個非常經典的案例,主要包括兩個特徵——Pizza直徑(單位:英寸)和Pizza價格(單位:美元)。假設讀者現在去到一家西餐廳,看到Pizza的選單,現在需要通過機器學習的方法構造一個一元線性迴歸模型,通過分析匹薩的直徑與價格的資料的線性關係,來預測任意直徑匹薩的價格。 資料集共十行,包括兩個特徵,如下表10.1所示。


2.線性迴歸分析

線性迴歸基礎步驟主要包括:
    1.匯入資料集,採用列表的形式定義直接和價格兩列資料。
    2.呼叫Scikit-learn機器學習包中線性迴歸模型。
    3.呼叫fit()函式對直徑和價格進行訓練。
    4.呼叫predice()函式對資料集進行預測。
    5.對線性迴歸演算法進行評價。
    6.視覺化分析並繪製相關圖形,直觀的呈現演算法模型的結果。
線性迴歸分析的完整程式碼如下:

# -*- coding: utf-8 -*-
from sklearn.linear_model import LinearRegression

#資料集 直徑、價格
x = [[5],[6],[7],[8],[10],[11],[13],[14],[16],[18]]
y = [[6],[7.5],[8.6],[9],[12],[13.6],[15.8],[18.5],[19.2],[20]]
print x
print y

clf = LinearRegression()
clf.fit(x,y)
pre = clf.predict([12])[0]
print(u'預測直徑為12英寸的價格: $%.2f' % pre)

通過呼叫sklearn機器學習包中linear_model子類的LinearRegression線性迴歸模型,然後fit()函式用來分析模型引數,predict()通過fit()算出模型引數構成的模型,對解釋變數進行預測獲得其結果。上面的程式碼輸出如下所示:

[[5], [6], [7], [8], [10], [11], [13], [14], [16], [18]]
[[6], [7.5], [8.6], [9], [12], [13.6], [15.8], [18.5], [19.2], [20]]
預測直徑為12英寸的價格: $14.42

可以發現直徑為12英寸的Pizza價格為14.42美元。同時它生成了一個一元線性迴歸模型,即:y = a*x + b。其中,y表示響應變數的預測值,這個示例為Pizza的價格預測值;x為因變數,表示Pizza的直徑。


3.視覺化分析

接下來需要對資料集進行視覺化分析,首先需要呼叫Matplotlib擴充套件包繪製直徑和價格的散點圖,程式碼如下:

# -*- coding: utf-8 -*-
from sklearn.linear_model import LinearRegression

#資料集 直徑、價格
x = [[5],[6],[7],[8],[10],[11],[13],[14],[16],[18]]
y = [[6],[7.5],[8.6],[9],[12],[13.6],[15.8],[18.5],[19.2],[20]]
print x
print y

clf = LinearRegression()
clf.fit(x,y)
pre = clf.predict([12])[0]
print(u'預測直徑為12英寸的價格: $%.2f' % pre)
x2 = [[0],[12],[15],[25]]
y2 = clf.predict(x2)

import matplotlib.pyplot as plt
plt.figure()
plt.rcParams['font.sans-serif'] = ['SimHei'] #指定預設字型
plt.title(u"線性迴歸預測Pizza直徑和價格")
plt.xlabel(u"x")
plt.ylabel(u"price")
plt.axis([0,25,0,25])
plt.scatter(x,y,marker="s",s=20)
plt.plot(x2,y2,"g-")
plt.show()

輸出圖形如下所示,其中(x2,y2)是訓練後的迴歸模型進行預測的結果,為一條直線。





二. 線性迴歸分析波士頓房價案例


1.資料集

波士頓房價資料集(Boston House Price Dataset)包含對房價的預測(以千美元計數),給定的條件是房屋及其相鄰房屋的詳細資訊。該資料集涉及一個迴歸問題,通過進行線性迴歸分析可以預測波斯頓房價資料。而且由於Sklearn機器學習包中已經自帶了該資料集,故直接引用該資料集,獲取其中某兩列資料,對其進行分析預測。

該資料集的下載地址為:http://lib.stat.cmu.edu/datasets/boston,也可以從UCI機器學習知識庫中下載,每個類的觀察值數量是均等的,共有 506 行資料,13 個輸入變數和1個輸出變數,資料集如下圖11.1所示,這些資料從1978年開始統計,涵蓋了波士頓不同郊區房屋14中特徵資訊。



在做資料分析過程中,通常需要將資料集劃分為訓練集和預測集,這裡作者將前406行作為訓練集,最後100行作為預測集,劃分程式碼如下:

# -*- coding: utf-8 -*-
#匯入資料集boston
from sklearn.datasets import load_boston
import numpy as np 
boston = load_boston()    
print boston.data.shape, boston.target.shape
print boston.data[0]
print boston.target

#劃分資料集
boston_temp = boston.data[:, np.newaxis, 5]   
x_train = boston_temp[:-100]      #訓練樣本  
x_test = boston_temp[-100:]       #測試樣本 後100行  
y_train = boston.target[:-100]    #訓練標記  
y_test = boston.target[-100:]     #預測對比標記

2.線性迴歸分析

線性迴歸過程主要如下:
    1.匯入資料集,波士頓房價資料。
    2.劃分資料集為訓練集和測試集,採用406和100的比例。
    3.匯入線性迴歸模型LinearRegression。
    4.對訓練集進行訓練操作,同時預測資料集結果。
    5.視覺化畫圖分析及結果評估。

線性迴歸分析波士頓房價資料集的程式碼如下:

# -*- coding: utf-8 -*-
from sklearn.datasets import load_boston
import numpy as np 
boston = load_boston()    
print boston.data.shape, boston.target.shape

#劃分資料集
boston_temp = boston.data[:, np.newaxis, 5]   
x_train = boston_temp[:-100]      #訓練樣本  
x_test = boston_temp[-100:]       #測試樣本 後100行  
y_train = boston.target[:-100]    #訓練標記  
y_test = boston.target[-100:]     #預測對比標記

#迴歸分析
from sklearn.linear_model import LinearRegression 
clf = LinearRegression()  
clf.fit(x_train, y_train)  

#演算法評估
pre = clf.predict(x_test)
print u"預測結果", pre
print u"真實結果", y_test
cost = np.mean(y_test-pre)**2  
print u'平方和計算:', cost  
print u'係數', clf.coef_   
print u'截距', clf.intercept_    
print u'方差', clf.score(x_test, y_test) 

#繪圖分析
import matplotlib.pyplot  as plt
plt.title(u'LinearRegression Boston')     
plt.xlabel(u'x')                   
plt.ylabel(u'price')          
plt.scatter(x_test, y_test, color = 'black')  
plt.plot(x_test, clf.predict(x_test), color='blue', linewidth = 3)
for idx, m in enumerate(x_test):  
    plt.plot([m, m],[y_test[idx],pre[idx]], 'r-')    
plt.show()   

對該演算法進行評估,線性迴歸演算法可以計算線性方程的係數和截距,即coef_為係數、intercept_為截距。同時可以通過clf.score(x_test,y_test)計算其方差。

平方和計算: 32.6621132918
係數 [ 9.52462596]
截距 -36.1965235122
方差 -1.83449598504  
輸出如下圖所示:





三. 隨機資料集線性迴歸分析和三維迴歸分析案例

1.隨機資料集

本章將生成一個隨機資料集供您使用,通過該資料集的線性迴歸分析,您也能瞭解到相關應用知識。同時,將進一步深入講解線性迴歸擬合方程的知識,希望本章對您有所幫助。

隨機數生成主要呼叫Numpy擴充套件包中的random函式或arange,呼叫函式arange(0,50,0.2)實現,隨機生成0到50個資料,其間隔為0.2。得到X資料集之後,作者隨機定義一個函式繪製對應的Y座標,再呼叫Matplotlib擴充套件包可以對資料集進行視覺化分析,並繪製相關的散點圖。核心程式碼如下:

import numpy as np
import math
X =  np.arange(0,50,0.2) 
print X
xArr = []
yArr = []
for n in X:
    xArr.append(n)
    y = 0.7*n + np.random.uniform(0,1)*math.sin(n)*2 - 3
    yArr.append(y)

import matplotlib.pyplot as plt
plt.plot(X, yArr, 'go')
plt.show()
輸出如下圖所示:


接下來需要呼叫Sklearn機器學習擴充套件包相關函式進行線性迴歸分析。


2.線性迴歸

完整程式碼如下:

# -*- coding: utf-8 -*-
import numpy as np
import math

#隨機數生成
X =  np.arange(0,50,0.2) 
print X
xArr = []
yArr = []
for n in X:
    xArr.append(n)
    y = 0.7*n + np.random.uniform(0,1)*math.sin(n)*2 - 3
    yArr.append(y)

#線性迴歸分析
from sklearn.linear_model import LinearRegression
clf = LinearRegression()
print clf
X =  np.array(X).reshape((len(X),1))     #list轉化為陣列
yArr = np.array(yArr).reshape((len(X),1))
clf.fit(X,yArr)
pre = clf.predict(X)

import matplotlib.pyplot as plt
plt.plot(X, yArr, 'go')
plt.plot(X, pre, 'r', linewidth=3)
plt.show()
輸出如下所示:



同時補充一段3D繪製的程式碼,隨機座標生成後,需要呼叫mpl_toolkits.mplot3d子類中Axes3D類生成對應的3D圖形。使用線性迴歸對其進行分析過程中,不同於二維視覺化分析,三維需要將xx和yy標定成輸入變數,zz為輸出變數進行訓練,再預測其結果。完整程式碼如下所示:
# -*- coding: utf-8 -*-
import numpy as np
from sklearn import linear_model
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import math

#linspace:開始值、終值和元素個數建立表示等差數列的一維陣列
xx, yy = np.meshgrid(np.linspace(0,10,20), np.linspace(0,100,20))
zz = 2.4 * xx + 4.5 * yy + np.random.randint(0,100,(20,20))
#構建成特徵、值的形式
X, Z = np.column_stack((xx.flatten(),yy.flatten())), zz.flatten()
#線性迴歸分析
regr = linear_model.LinearRegression()
regr.fit(X, Z)
#預測的一個特徵
x_test = np.array([[15.7, 91.6]])
print regr.predict(x_test)
#畫圖視覺化分析
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(xx, yy, zz) #真實點
#擬合的平面
ax.plot_wireframe(xx, yy, regr.predict(X).reshape(20,20))
ax.plot_surface(xx, yy, regr.predict(X).reshape(20,20), alpha=0.3)
plt.show()
輸出如下圖所示:



四. Pizza資料集一元和多元線性迴歸分析


完整程式碼如下:

# -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 23:31:16 2017

@author: yxz15
"""

# -*- coding: utf-8 -*-
from sklearn.linear_model import LinearRegression

#資料集 直徑、價格
x = [[5],[6],[7],[8],[10],[11],[13],[14],[16],[18]]
y = [[6],[7.5],[8.6],[9],[12],[13.6],[15.8],[18.5],[19.2],[20]]
print x
print y

clf = LinearRegression()
clf.fit(x,y)
pre = clf.predict([12])[0]
print(u'預測直徑為12英寸的價格: $%.2f' % pre)
x2 = [[0],[12],[15],[25]]
y2 = clf.predict(x2)

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
plt.axis([0,25,0,25])
plt.scatter(x,y,marker="s",s=20)
plt.plot(x2,y2,"g-")

#匯入多項式迴歸模型
from sklearn.preprocessing import PolynomialFeatures
xx = np.linspace(0,25,100) #0到25等差數列
quadratic_featurizer = PolynomialFeatures(degree = 2) #例項化一個二次多項式
x_train_quadratic = quadratic_featurizer.fit_transform(x) #用二次多項式多樣本x做變換
X_test_quadratic = quadratic_featurizer.transform(x2)
regressor_quadratic = LinearRegression()
regressor_quadratic.fit(x_train_quadratic, y)
xx_quadratic = quadratic_featurizer.transform(xx.reshape(xx.shape[0], 1))# 把訓練好X值的多項式特徵例項應用到一系列點上,形成矩陣

plt.plot(xx, regressor_quadratic.predict(xx_quadratic),
         label="$y = ax^2 + bx + c$",linewidth=2,color="r")
plt.legend()
plt.show()
輸出如下圖所示:

四次方擬合,核心程式碼如下:

#匯入多項式迴歸模型
from sklearn.preprocessing import PolynomialFeatures
xx = np.linspace(0,25,100) #0到25等差數列
quadratic_featurizer = PolynomialFeatures(degree = 4) #例項化一個二次多項式
x_train_quadratic = quadratic_featurizer.fit_transform(x) #用二次多項式多樣本x做變換
X_test_quadratic = quadratic_featurizer.transform(x2)
regressor_quadratic = LinearRegression()
regressor_quadratic.fit(x_train_quadratic, y)
xx_quadratic = quadratic_featurizer.transform(xx.reshape(xx.shape[0], 1))# 把訓練好X值的多項式特徵例項應用到一系列點上,形成矩陣

plt.plot(xx, regressor_quadratic.predict(xx_quadratic),
         label="$y = ax^4 + bx + c$",linewidth=2,color="r")
plt.legend()
plt.show()
輸出如下圖所示:


希望文章對你有所幫助,尤其是我的學生,如果文章中存在錯誤或不足之處,還請海涵。給綠么準備驚喜中~
(By:Eastmount 2017-11-26 深夜12點  http://blog.csdn.net/eastmount/ )


相關文章