Python進(jìn)行統(tǒng)計(jì)建模
前言
大家好,在之前的文章中我們已經(jīng)講解了很多Python數(shù)據(jù)處理的方法比如讀取數(shù)據(jù)、缺失值處理、數(shù)據(jù)降維等,也介紹了一些數(shù)據(jù)可視化的方法如Matplotlib、pyecharts等,那么在掌握了這些基礎(chǔ)技能之后,要進(jìn)行更深入的分析就需要掌握一些常用的建模方法,本文將講解如何利用Python進(jìn)行統(tǒng)計(jì)分析。和之前的文章類似,本文只講如何用代碼實(shí)現(xiàn),不做理論推導(dǎo)與過多的結(jié)果解釋(事實(shí)上常用的模型可以很輕松的查到完美的推導(dǎo)與解析)。因此讀者需要掌握一些基本的統(tǒng)計(jì)模型比如回歸模型、時間序列等。
Statsmodels簡介
在Python 中統(tǒng)計(jì)建模分析最常用的就是Statsmodels模塊。Statsmodels是一個主要用來進(jìn)行統(tǒng)計(jì)計(jì)算與統(tǒng)計(jì)建模的Python庫。主要有以下功能:
- 探索性分析:包含列聯(lián)表、鏈?zhǔn)椒匠潭嘀夭逖a(bǔ)等探索性數(shù)據(jù)分析方法以及與統(tǒng)計(jì)模型結(jié)果的可視化圖表,例如擬合圖、箱線圖、相關(guān)圖、時間序列圖等
- 回歸模型:線性回歸模型、非線性回歸模型、廣義線性模型、線性混合效應(yīng)模型等
- 其他功能:方差分析、時間序列分析等模型的參數(shù)估計(jì)與估計(jì)參數(shù)的假設(shè)檢驗(yàn)等
安裝 brew install Statsmodels
文檔 github.com/statsmodels/statsmodels
線性回歸模型:普通最小二乘估計(jì)
線性模型有普通最小二乘(OLS)廣義最小二乘(GLS)、加權(quán)最小二乘(WLS)等,Statsmodels對線性模型有較好的支持,來看個最簡單的例子:普通最小二乘(OLS)
首先導(dǎo)入相關(guān)包
%matplotlib inline import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt from statsmodels.sandbox.regression.predstd import wls_prediction_std np.random.seed(9876789)
然后創(chuàng)建數(shù)據(jù),先設(shè)置樣本量為100
nsample = 100 #樣本數(shù)量
然后設(shè)置x1和x2,x1是0到10等差排列,x2是x1的平方
x = np.linspace(0, 10, 100) X = np.column_stack((x, x**2))
再設(shè)置beta、誤差項(xiàng)與響應(yīng)變量y
beta = np.array([1, 0.1, 10]) e = np.random.normal(size=nsample) X = sm.add_constant(X) y = np.dot(X, beta) + e
接著建立回歸模型
model = sm.OLS(y, X) results = model.fit() print(results.summary())
查看模型結(jié)果
是不是和R語言輸出的結(jié)果形式很接近?回歸系數(shù)值、P-value、R-squared等評估回歸模型的參數(shù)值全部都有,還可以使用dir(results)獲得全部變量的值并調(diào)取出來
print('Parameters: ', results.params) print('R2: ', results.rsquared)
那么回歸模型的就是y=1.3423-0.0402x1+10.0103x2,當(dāng)然這個模型可以繼續(xù)優(yōu)化那么就交給讀者完成。接下來我們來繪制一下樣本點(diǎn)與回歸曲線
y_fitted = results.fittedvalues fig, ax = plt.subplots(figsize=(8,6)) ax.plot(x, y, 'o', label='data') ax.plot(x, y_fitted, 'r--.',label='OLS') ax.legend(loc='best')
時間序列:ARMA
關(guān)于時間序列的模型有很多,我們選擇ARMA模型示例,首先導(dǎo)入相關(guān)包并生成數(shù)據(jù)
%matplotlib inline import numpy as np import statsmodels.api as sm import pandas as pd from statsmodels.tsa.arima_process import arma_generate_sample np.random.seed(12345) arparams = np.array([.75, -.25]) maparams = np.array([.65, .35]) arparams = np.r_[1, -arparams] maparams = np.r_[1, maparams] nobs = 250 y = arma_generate_sample(arparams, maparams, nobs)
接著,我們可以添加一些日期信息。對于本例,我們將使用pandas時間序列并建立模型
dates = sm.tsa.datetools.dates_from_range('1980m1', length=nobs) y = pd.Series(y, index=dates) arma_mod = sm.tsa.ARMA(y, order=(2,2)) arma_res = arma_mod.fit(trend='nc', disp=-1)
最后再做一下預(yù)測
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10,8)) fig = arma_res.plot_predict(start='1999-06-30', end='2001-05-31', ax=ax) legend = ax.legend(loc='upper left')
回歸診斷:估計(jì)回歸模型
首先導(dǎo)入相關(guān)包
%matplotlib inline from statsmodels.compat import lzip import numpy as np import pandas as pd import statsmodels.formula.api as smf import statsmodels.stats.api as sms import matplotlib.pyplot as plt
然后加載數(shù)據(jù)
url = 'https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/HistData/Guerry.csv' dat = pd.read_csv(url)
擬合模型
results = smf.ols('Lottery ~ Literacy + np.log(Pop1831)', data=dat).fit()
查看結(jié)果
print(results.summary())
回歸診斷:殘差的正態(tài)性
Jarque-Bera test:
name = ['Jarque-Bera', 'Chi^2 two-tail prob.', 'Skew', 'Kurtosis'] test = sms.jarque_bera(results.resid) lzip(name, test) ####結(jié)果 [('Jarque-Bera', 3.3936080248431666), ('Chi^2 two-tail prob.', 0.1832683123166337), ('Skew', -0.48658034311223375), ('Kurtosis', 3.003417757881633)]
Omni test:
name = ['Chi^2', 'Two-tail probability'] test = sms.omni_normtest(results.resid) lzip(name, test) ####結(jié)果 [('Chi^2', 3.713437811597181), ('Two-tail probability', 0.15618424580304824)]
回歸診斷:異方差
Breush-Pagan test:
name = ['Lagrange multiplier statistic', 'p-value', 'f-value', 'f p-value'] test = sms.het_breuschpagan(results.resid, results.model.exog) lzip(name, test) ###結(jié)果 [('Lagrange multiplier statistic', 4.893213374093957), ('p-value', 0.08658690502352209), ('f-value', 2.503715946256434), ('f p-value', 0.08794028782673029)] Goldfeld-Quandt test
name = ['F statistic', 'p-value']
test = sms.het_goldfeldquandt(results.resid, results.model.exog)
lzip(name, test)
####結(jié)果
[('F statistic', 1.1002422436378152), ('p-value', 0.3820295068692507)]
回歸診斷:多重共線性
檢查多重共線性可以使用
np.linalg.cond(results.model.exog)
結(jié)果是702.1792145490062,說明存在較強(qiáng)多重共線性。
結(jié)束語
以上就是Statsmodels的基本功能介紹,如果熟悉R的讀者會發(fā)現(xiàn)很多命令與R是類似的。最后想多說一句,全文沒有出現(xiàn)太多模型的理論知識,因?yàn)檫@些模型的推導(dǎo)過程隨便百度一搜都能得到十分詳細(xì)的優(yōu)質(zhì)回答,因此在學(xué)會如何用計(jì)算機(jī)實(shí)現(xiàn)之后必須要回過頭去理解模型里每一個參數(shù)是怎樣得到,又有哪些含義才算真正搞定。
以上就是Python進(jìn)行統(tǒng)計(jì)建模的詳細(xì)內(nèi)容,更多關(guān)于Python統(tǒng)計(jì)建模的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python啟動UDP服務(wù),監(jiān)聽并接收客戶端數(shù)據(jù)方式
這篇文章主要介紹了Python啟動UDP服務(wù),監(jiān)聽并接收客戶端數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07Django之form組件自動校驗(yàn)數(shù)據(jù)實(shí)現(xiàn)
這篇文章主要介紹了Django之form組件自動校驗(yàn)數(shù)據(jù)實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01