生活随笔
收集整理的這篇文章主要介紹了
多元线性回归分析练习题
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
表 11.2 數(shù)據(jù)
python代碼
import pandas as pd
import statsmodels.api as sm
ex922 = pd.read_csv('D:ex922.csv',encoding='gbk')
values = ['人口數(shù)量X1','蔬菜價(jià)銷量X2','瓜果人均銷量X3','副食人均銷量X4','糧食人均銷量X5']
factors = ['X1','X2','X3','X4','X5']
def Morelinear(value,name):X=ex922[value]X=sm.add_constant(X)y = ex922[name]est=sm.OLS(y,X).fit()
return estdef Delsomefactor(): #刪除不顯著的因素result = Morelinear(values,'蔬菜總銷量Y')results = result.pvalues.tolist()for i in range(1,len(results)):if(results[i]<0.05):break;while(result.fvalue > result.f_pvalue):c=[] #放位置cc=[] #放值for i in range(1,len(result.pvalues)):if(result.pvalues[i]>0.05): #選出影響不顯著的因素cc.append(result.pvalues[i])c.append(i)if(len(cc)==0):breakelse:maxvalue = max(cc) #挑出最不顯著的值index = cc.index(maxvalue) indexvalue = c[index] -1 #找出其位置del(values[indexvalue])del(factors[indexvalue])result = Morelinear (values,'蔬菜總銷量Y')results = result.pvalues.tolist()
return resultdef Linermodel(): #構(gòu)造回歸模型finalresult = Delsomefactor()finalresult.params.index[1:]l=len(finalresult.params)print('Y=',end='')for i in range(l):if(i == 0):print(finalresult.params[i], end='+')elif(i!=l-1):if(finalresult.params[i+1]>0):print(finalresult.params[i],'*',factors[i-1], end='+')else:print(finalresult.params[i],'*',factors[i-1],end='')elif(i== (l-1)):print(finalresult.params[i],'*',factors[i-1])return finalresult
執(zhí)行
fres = Linermodel()
得出結(jié)果
查看回歸系數(shù)顯著的因素
擬合效果圖
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import pylab as mpl
import pandas as pd
# 解決可視化不能顯示中文和符號(hào)問題:
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['axes.unicode_minus'] = False
plt.rcParams.update(params)
plt.rcParams['savefig.dpi'] = 10 #圖片像素
plt.rcParams['figure.dpi'] = 300 #分辨率
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
xmajorLocator = MultipleLocator(2) #將x主刻度標(biāo)簽設(shè)置為20的倍數(shù)
import matplotlib.ticker as ticker
Y1=ex922['蔬菜總銷量Y']
X=ex922['年份']
X1=ex922['人口數(shù)量X1']
X2=ex922['蔬菜價(jià)銷量X2']
X4=ex922['副食人均銷量X4']
Y2=1.842710490517286+0.01575305045025612 * X1-0.46540638240138626 * X2+0.16284729866888398 * X4X=X.tolist()
plt.plot(X,Y,label="真實(shí)值")
plt.plot(X,Y2,label="模型值")
plt.xlabel("年份")
plt.ylabel("蔬菜總銷量")
plt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter('%d')) #x軸取整數(shù)
plt.gca().yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.1f')) #x軸取整數(shù)
plt.legend(loc='best')
plt.show()
結(jié)果圖
上一篇:數(shù)據(jù)挖掘之回歸分析
下一篇:批量下載數(shù)據(jù)集
總結(jié)
以上是生活随笔為你收集整理的多元线性回归分析练习题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。