在計量經(jīng)濟學里面的研究,圍繞著影響GDP的因素的研究有很多,基本都是做回歸,拿GDP作為被解釋變量y,其他因素作為解釋變量x。然后做線性回歸,時間序列就做自回歸,面板數(shù)據(jù)就做固定效應(yīng)等等。本次案例采用機器學習里面的隨機森林回歸來研究影響經(jīng)濟增長的因素,使用Python編程。選取人口,固定資產(chǎn)投資,消費,凈出口,稅收,廣義M2貨幣,物價指數(shù)CPI作為解釋變量X。我國GDP作為被解釋變量y。
數(shù)據(jù)長這個樣子,從1990年到2020年
這個數(shù)據(jù)還挺熱門的,需要這代碼演示數(shù)據(jù)的同學可以參考:數(shù)據(jù)
首先導入包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
import statsmodels.formula.api as smf
plt.rcParams ['font.sans-serif'] ='SimHei'
plt.rcParams ['axes.unicode_minus']=False
sns.set_style("darkgrid",{"font.sans-serif":[ 'Arial']})
#plt.rcParams['font.sans-serif'] = ['KaiTi']
讀取數(shù)據(jù),查看數(shù)據(jù)信息
spss = pd.read_excel('data.xlsx')
spss.info()
data=spss.copy()
?將時間設(shè)為索引
spss.set_index('year',inplace=True)
data.drop('year',axis=1,inplace=True)
?描述性統(tǒng)計
data.describe()
計算每個變量的均值方差,分位數(shù)等
畫出每個變量的隨時間變化的折線圖
#Sequence diagram of eight variables
column = data.columns.tolist()
fig = plt.figure(figsize=(12,4), dpi=128)
for i in range(8):
plt.subplot(2,4, i + 1)
sns.lineplot(data=spss[column[i]],lw=1)
plt.ylabel(column[i], fontsize=12)
plt.tight_layout()
plt.show()
?所有變量都是單調(diào)增加,具有一致性趨勢。
畫所有變量的箱線圖
#boxplot
column = data.columns.tolist()
fig = plt.figure(figsize=(12,4), dpi=128)
for i in range(8):
plt.subplot(2,4, i + 1)
sns.boxplot(data=data[column[i]], orient="v",width=0.5)
plt.ylabel(column[i], fontsize=12)
plt.tight_layout()
plt.show()
畫核密度圖
#kdeplot
column = data.columns.tolist()
fig = plt.figure(figsize=(12,4), dpi=128)
for i in range(8):
plt.subplot(2,4, i + 1)
sns.kdeplot(data=data[column[i]],color='blue',shade= True)
plt.ylabel(column[i], fontsize=12)
plt.tight_layout()
plt.show()
?
?從箱線圖和核密度圖可以看出數(shù)據(jù)的分布都還比較集中,沒有很多異常點。
下面畫所有變量兩兩之間的散點圖
sns.pairplot(data[column],diag_kind='kde')
plt.savefig('Scatter plot.jpg',dpi=256)
?可以看到除了cpi,幾乎所有變量之間都有線性關(guān)系,人口有點像二次拋物線。
畫皮爾遜相關(guān)系數(shù)熱力圖
#Pearson's correlation coefficient heatmap
corr = plt.figure(figsize = (10,10),dpi=128)
corr= sns.heatmap(data[column].corr(),annot=True,square=True)
plt.xticks(rotation=40)
?很多X之間都存在的高的相關(guān)性,經(jīng)典的最小二乘線性模型可能存在著嚴重的多重共線性。
線性回歸
還是做一下線性回歸
import statsmodels.formula.api as smf
all_columns = "+".join(data.columns[1:])
print('x is :'+all_columns)
formula = 'GDP~' + all_columns
print('The regression equation is :'+formula)
寫出回歸方程后,帶入ols模型
results = smf.ols(formula, data=data).fit()
results.summary()
?
?可以看到整體的擬合優(yōu)度為100。。在0.05的顯著性水平下,人口和消費,還有凈出口稅收都對GDP的變動具有顯著性的影響。
有些變量不顯著,可能是多重共線性的原因……下面的非參數(shù)回歸方法——隨機森林,可以避免多重共線性的影響,還能得到變量的重要特征排序
隨機森林回歸
取出X和y
X=data.iloc[:,1:]
y=data.iloc[:,0]
數(shù)據(jù)標準化
# data normalization
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X)
X_s= scaler.transform(X)
X_s[:3]
?隨機森林模型擬合和評價
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_estimators=5000, max_features=int(X.shape[1] / 3), random_state=0)
model.fit(X_s,y)
model.score(X_s,y)
?擬合優(yōu)度也很高,99.96%
下面對比擬合值和真實值
pred = model.predict(X_s)
plt.scatter(pred, y, alpha=0.6)
w = np.linspace(min(pred), max(pred), 100)
plt.plot(w, w)
plt.xlabel('pred')
plt.ylabel('y_test')
plt.title('Comparison of GDP fitted value and true value')
?可以看到兩者基本都在一條線上,說明效果很好
計算每個變量的重要性
print(model.feature_importances_)
sorted_index = model.feature_importances_.argsort()
畫圖可視化
plt.barh(range(X.shape[1]), model.feature_importances_[sorted_index])
plt.yticks(np.arange(X.shape[1]),X.columns[sorted_index],fontsize=14)
plt.xlabel('X Importance',fontsize=12)
plt.ylabel('covariate X',fontsize=12)
plt.title('Importance Ranking Plot of Covariate ',fontsize=15)
plt.tight_layout()
?
?結(jié)論,影響GDP的變量重要性排序:
稅收>M2>消費>投資>人口>出口進口量>CPI
當然實際科研中也可以選擇更多的變量,隨機森林不怕多重共線性,是要變量越多越好。文章來源:http://www.zghlxwxcb.cn/news/detail-489199.html
創(chuàng)作不易,看官覺得寫得還不錯的話點個關(guān)注和贊吧,本人會持續(xù)更新python數(shù)據(jù)分析領(lǐng)域的代碼文章~(需要定制代碼可私信)文章來源地址http://www.zghlxwxcb.cn/news/detail-489199.html
到了這里,關(guān)于Python數(shù)據(jù)分析案例05——影響經(jīng)濟增長的因素(隨機森林回歸)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!