日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

python3 線性回歸驗(yàn)證方法

系統(tǒng) 2523 0

如下所示:

            
#-*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from patsy.highlevel import dmatrices
#2.7里面是from patsy import dmatrices
from statsmodels.stats.outliers_influence import variance_inflation_factor
import statsmodels.api as sm
import scipy.stats as stats
from sklearn.metrics import mean_squared_error
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib
 
#數(shù)據(jù)獲取
ccpp = pd.read_excel('CCPP.xlsx')
ccpp.describe()
#繪制各變量之間的散點(diǎn)圖
sns.pairplot(ccpp)
plt.show()
#發(fā)電量(PE)與自變量之間的相關(guān)系數(shù)
a = ccpp.corrwith(ccpp.PE)
print(a)
#將因變量PE,自變量AT,V,AP和截距項(xiàng)(值為1的1維數(shù)值)以數(shù)據(jù)框的形式組合起來
y,x = dmatrices('PE~AT+V+AP',data = ccpp,return_type = 'dataframe')
#構(gòu)造空的數(shù)據(jù)框
vif = pd.DataFrame()
vif[""VIF Factor""] = [variance_inflation_factor(x.values,i) for i in range(x.shape[1])]
vif[""features""] = x.columns
print (vif)
 
#構(gòu)建PE與AT,V和AP之間的線性模型
fit = sm.formula.ols('PE~AT+V+AP',data=ccpp).fit()
b = fit.summary()
# print(b)
#計(jì)算模型的RMSE值
pred = fit.predict()
c = np.sqrt(mean_squared_error(ccpp.PE,pred))
print(c)
#離群點(diǎn)檢驗(yàn)
outliers = fit.get_influence()
#高杠桿值點(diǎn)(帽子矩陣)
leverage = outliers.hat_matrix_diag
#dffits值
dffits = outliers.dffits[0]
#學(xué)生化殘差
resid_stu = outliers.resid_studentized_external
#cook距離
cook = outliers.cooks_distance[0]
#covratio值
covratio = outliers.cov_ratio
#將上面的幾種異常值檢驗(yàn)統(tǒng)計(jì)量與原始數(shù)據(jù)集合并
contat1 = pd.concat([pd.Series(leverage,name = 'leverage'),pd.Series(dffits,name ='dffits'),
pd.Series(resid_stu,name = 'resid_stu'),pd.Series(cook,name = 'cook'),
pd.Series(covratio,name ='covratio'),],axis = 1)
ccpp_outliers = pd.concat([ccpp,contat1],axis = 1)
d = ccpp_outliers.head()
print(d)
 
#計(jì)算異常值數(shù)量的比例
outliers_ratio = sum(np.where((np.abs(ccpp_outliers.resid_stu)>2),1,0))/ccpp_outliers.shape[0]
e = outliers_ratio
print(e)
#刪除異常值
ccpp_outliers = ccpp_outliers.loc[np.abs(ccpp_outliers.resid_stu)<=2,]
#重新建模
fit2 = sm.formula.ols('PE~AT+V+AP',data = ccpp_outliers).fit()
f = fit2.summary()
# print(f)
pred2 = fit2.predict()
g = np.sqrt(mean_squared_error(ccpp_outliers.PE,pred2))
print(g)
#
#殘差的正態(tài)性檢驗(yàn)(直方圖法)
resid = fit2.resid
#中文和負(fù)號(hào)的正常顯示
# plt.rcParams['font.sans=serif'] = ['Microsoft YaHei']
plt.rcParams['font.sans-serif'] = ['SimHei']
# plt.rcParams['font.sans=serif'] = 'sans-serif'
plt.rcParams['axes.unicode_minus'] = False
plt.hist(resid,bins = 100,normed = True,color = 'steelblue',edgecolor = 'k')
#設(shè)置坐標(biāo)軸標(biāo)簽和標(biāo)題
plt.title('殘差直方圖')
plt.ylabel('密度值')
#生成正態(tài)曲線的數(shù)據(jù)
x1 = np.linspace(resid.min(),resid.max(),1000)
normal = mlab.normpdf(x1,resid.mean(),resid.std())
#繪制正態(tài)分布曲線
plt.plot(x1,normal,'r-',linewidth = 2,label = '正態(tài)分布曲線')
#生成核密度曲線的數(shù)據(jù)
kde = mlab.GaussianKDE(resid)
x2 = np.linspace(resid.min(),resid.max(),1000)
#繪制核密度曲線
plt.plot(x2,kde(x2),'k-',linewidth = 2,label = '核密度曲線')
#去除圖形頂部邊界和右邊界的刻度
plt.tick_params(top = 'off',right = 'off')
#顯示圖例
plt.legend(loc='best')
#顯示圖形
plt.show()
#生成的正態(tài)曲線的數(shù)據(jù)
pp_qq_plot = sm.ProbPlot(resid)
pp_qq_plot.ppplot(line = '45')
plt.title('P-P圖')
pp_qq_plot.qqplot(line = 'q')
plt.title('Q-Q圖')
plt.show()
#殘差的正態(tài)性檢驗(yàn)(非參數(shù)法)
standard_resid = (resid-np.mean(resid))/np.std(resid)
g = stats.kstest(standard_resid,'norm')
print(g)
# 總結(jié):由于shapiro正態(tài)性檢驗(yàn)對(duì)樣本量的需求是5000以內(nèi),而本次數(shù)據(jù)集樣本量有9000多,故選擇k-s來完成正態(tài)性檢驗(yàn)。
# 從k-s檢驗(yàn)的p值來看,拒絕了殘差服從正態(tài)分布的假設(shè),即認(rèn)為殘差并不滿足正態(tài)性假設(shè)這個(gè)前提。
# 如果殘差不服從正態(tài)分布的話,建議對(duì)Y變量進(jìn)行box-cox變換處理。
# 由于fit2模型的殘差并沒有特別明顯的偏態(tài)(偏度為0.058,接近于0),故這里就不對(duì)Y進(jìn)行變換。
 
# 
# import scipy.stats as stats
# #找到box-cox變換的Lambda系數(shù)
# lamd = stats.boxcox_normmax(vif.y,method = 'mle')
# #對(duì)y進(jìn)行變換
# vif['trans_y'] = stats.boxcox(vif.y,lamd)
# #建模
# fit3 = sm.formula.ols('y~x1+x2...',data = vif).fit()
# fit3.summary()

          

以上這篇python3 線性回歸驗(yàn)證方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 长武县| 兴海县| 新乡县| 萝北县| 定安县| 乡城县| 贞丰县| 乌什县| 陕西省| 绥江县| 新兴县| 汨罗市| 泰兴市| 玉环县| 渭南市| 呼玛县| 安岳县| 伊川县| 白河县| 南丰县| 神木县| 垣曲县| 禹城市| 自治县| 灵台县| 景谷| 南平市| 鹤峰县| 枝江市| 贵港市| 金溪县| 陵水| 宝坻区| 阿合奇县| 朝阳市| 丽水市| 龙川县| 鲁山县| 邢台县| 伊吾县| 郸城县|