基于教材第九章相关与回归及Python分析¶
9.1 变量间的关系¶
9.2 一元相关与回归分析¶
9.2.1 简单相关分析¶
In [2]:
Copied!
%run init.py
%run init.py
In [4]:
Copied!
import numpy as np
np.set_printoptions(4)
x=np.array([171,175,159,155,152,158,154,164,168,166,159,164]) #身高向量
y=np.array([57,64,41,38,35,44,41,51,57,49,47,46]) #体重向量
import numpy as np
np.set_printoptions(4)
x=np.array([171,175,159,155,152,158,154,164,168,166,159,164]) #身高向量
y=np.array([57,64,41,38,35,44,41,51,57,49,47,46]) #体重向量
In [6]:
Copied!
%config InlineBackend.figure_format='retina'
import matplotlib.pyplot as plt #加载基本绘图包
plt.scatter(x,y); #做散点图
plt.xlabel('x');plt.ylabel('y');
%config InlineBackend.figure_format='retina'
import matplotlib.pyplot as plt #加载基本绘图包
plt.scatter(x,y); #做散点图
plt.xlabel('x');plt.ylabel('y');
In [8]:
Copied!
def lxy(x,y):return sum(x*y)-sum(x)*sum(y)/len(x) #离均差乘积和函数
def lxy(x,y):return sum(x*y)-sum(x)*sum(y)/len(x) #离均差乘积和函数
In [10]:
Copied!
lxy(x,x) #x的离均差平方和
lxy(x,x) #x的离均差平方和
Out[10]:
556.9166666666861
In [12]:
Copied!
lxy(y,y) #y的离均差平方和
lxy(y,y) #y的离均差平方和
Out[12]:
813.0
In [14]:
Copied!
lxy(x,y) #x和y的离均差乘积和
lxy(x,y) #x和y的离均差乘积和
Out[14]:
645.5
In [16]:
Copied!
r=lxy(x,y)/np.sqrt(lxy(x,x)*lxy(y,y)) ;r #相关系数计算
r=lxy(x,y)/np.sqrt(lxy(x,x)*lxy(y,y)) ;r #相关系数计算
Out[16]:
0.95930314057057
In [18]:
Copied!
np.corrcoef(x,y) #计算相关系数
np.corrcoef(x,y) #计算相关系数
Out[18]:
array([[1. , 0.9593],
[0.9593, 1. ]])
In [20]:
Copied!
n=len(x) #向量的长度
tr=r/np.sqrt((1-r**2)/(n-2)) #相关系数假设检验t统计量
tr
n=len(x) #向量的长度
tr=r/np.sqrt((1-r**2)/(n-2)) #相关系数假设检验t统计量
tr
Out[20]:
10.742975886487837
In [22]:
Copied!
#from scipy import stats as st #加载统计包
import scipy.stats as st #加载统计包
rp=st.pearsonr(x,y)
print('r=%.4f p-value=%.4g'%(rp[0],rp[1]))
#from scipy import stats as st #加载统计包
import scipy.stats as st #加载统计包
rp=st.pearsonr(x,y)
print('r=%.4f p-value=%.4g'%(rp[0],rp[1]))
r=0.9593 p-value=8.21e-07
9.2.2 简单回归分析¶
In [25]:
Copied!
b=lxy(x,y)/lxy(x,x) #线性回归方程斜率
a=y.mean()-b*x.mean() #线性回归方程截距
print('a=%.4f b=%.4f'%(a,b)) #显示线性回归方程估计值
b=lxy(x,y)/lxy(x,x) #线性回归方程斜率
a=y.mean()-b*x.mean() #线性回归方程截距
print('a=%.4f b=%.4f'%(a,b)) #显示线性回归方程估计值
a=-140.3644 b=1.1591
In [27]:
Copied!
plt.plot(x,y,'o',x,a+b*x,'-'); #添加估计方程线
plt.xlabel('x');plt.ylabel('y');
plt.plot(x,y,'o',x,a+b*x,'-'); #添加估计方程线
plt.xlabel('x');plt.ylabel('y');
In [29]:
Copied!
import pandas as pd #加载数据分析包
pd.set_option('display.precision',4) #设置数据框输出精度
d93=pd.read_excel('mvsData.xlsx','d93',index_col=0);d93
import pandas as pd #加载数据分析包
pd.set_option('display.precision',4) #设置数据框输出精度
d93=pd.read_excel('mvsData.xlsx','d93',index_col=0);d93
Out[29]:
| y | x | |
|---|---|---|
| Year | ||
| 1978 | 11.3226 | 5.19 |
| 1979 | 11.4638 | 5.38 |
| 1980 | 11.5993 | 5.72 |
| 1981 | 11.7579 | 6.30 |
| 1982 | 12.1233 | 7.00 |
| ... | ... | ... |
| 2014 | 1403.7003 | 1191.75 |
| 2015 | 1522.6923 | 1249.22 |
| 2016 | 1596.0497 | 1303.61 |
| 2017 | 1725.9277 | 1443.70 |
| 2018 | 1833.5984 | 1564.03 |
41 rows × 2 columns
In [31]:
Copied!
from statsmodels.formula.api import ols #加载公式法普通最小二乘函数
fm0=ols('y ~ x',data=d93).fit() #拟合一元线性回归模型
fm0.params #显示回归参数
from statsmodels.formula.api import ols #加载公式法普通最小二乘函数
fm0=ols('y ~ x',data=d93).fit() #拟合一元线性回归模型
fm0.params #显示回归参数
Out[31]:
Intercept -9.0593 x 1.1895 dtype: float64
In [33]:
Copied!
plt.plot(d93.x,d93.y,'o',d93.x,fm0.fittedvalues,'-'); #添加回归线
plt.xlabel('x');plt.ylabel('y');
plt.plot(d93.x,d93.y,'o',d93.x,fm0.fittedvalues,'-'); #添加回归线
plt.xlabel('x');plt.ylabel('y');
In [35]:
Copied!
#import statsmodels.api as sm #加载统计分析模型包
#sm.stats.anova_lm(fm0) #模型方差分析
#import statsmodels.api as sm #加载统计分析模型包
#sm.stats.anova_lm(fm0) #模型方差分析
In [37]:
Copied!
print(fm0.summary().tables[1]) #回归系数t检验
print(fm0.summary().tables[1]) #回归系数t检验
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept -9.0593 3.321 -2.728 0.009 -15.776 -2.343
x 1.1895 0.006 209.775 0.000 1.178 1.201
==============================================================================
9.3 多元相关与回归分析¶
9.3.1 多元线性相关分析¶
In [41]:
Copied!
d94=pd.read_excel('mvsData.xlsx','d94',index_col=0); d94
d94=pd.read_excel('mvsData.xlsx','d94',index_col=0); d94
Out[41]:
| y | x1 | x2 | x3 | x4 | |
|---|---|---|---|---|---|
| Year | |||||
| 1978 | 11.3226 | 36.34 | 5.19 | 3.5500 | 406.82 |
| 1979 | 11.4638 | 40.78 | 5.38 | 4.1200 | 415.92 |
| 1980 | 11.5993 | 45.75 | 5.72 | 5.7000 | 429.03 |
| 1981 | 11.7579 | 49.57 | 6.30 | 8.9040 | 441.65 |
| 1982 | 12.1233 | 54.26 | 7.00 | 12.8010 | 456.74 |
| ... | ... | ... | ... | ... | ... |
| 2014 | 1403.7003 | 6471.82 | 1191.75 | 2632.0878 | 796.90 |
| 2015 | 1522.6923 | 6991.09 | 1249.22 | 2566.9413 | 800.91 |
| 2016 | 1596.0497 | 7456.32 | 1303.61 | 2556.6712 | 806.94 |
| 2017 | 1725.9277 | 8152.60 | 1443.70 | 2683.7033 | 806.86 |
| 2018 | 1833.5984 | 8844.26 | 1564.03 | 3172.4559 | 805.25 |
41 rows × 5 columns
In [43]:
Copied!
print(d94.corr()) #多元数据相关系数矩阵
print(d94.corr()) #多元数据相关系数矩阵
y x1 x2 x3 x4 y 1.0000 0.9978 0.9996 0.9708 0.6521 x1 0.9978 1.0000 0.9984 0.9769 0.6911 x2 0.9996 0.9984 1.0000 0.9760 0.6641 x3 0.9708 0.9769 0.9760 1.0000 0.7348 x4 0.6521 0.6911 0.6641 0.7348 1.0000
In [45]:
Copied!
%config InlineBackend.figure_format='retina' #可提高图形显示的清晰度
pd.plotting.scatter_matrix(d94); #多元数据散点图
%config InlineBackend.figure_format='retina' #可提高图形显示的清晰度
pd.plotting.scatter_matrix(d94); #多元数据散点图
In [47]:
Copied!
import scipy.stats as st #加载统计包
def mcor_test(X): #相关系数矩阵检验
p=X.shape[1];p
sp=np.ones([p, p]).astype(str)
for i in range(0,p):
for j in range(i,p):
P=st.pearsonr(X.iloc[:,i],X.iloc[:,j])[1]
if P>0.05: sp[i,j]=' '
if(P>0.01 and P<=0.05): sp[i,j]='*'
if(P>0.001 and P<=0.01): sp[i,j]='**'
if(P<=0.001): sp[i,j]='***'
r=st.pearsonr(X.iloc[:,i],X.iloc[:,j])[0]
sp[j,i]=round(r,4)
if(i==j):sp[i,j]='------'
print(pd.DataFrame(sp,index=X.columns,columns=X.columns))
print("\n下三角为相关系数,上三角为检验p值 * p<0.05 ** p<0.05 *** p<0.001")
import scipy.stats as st #加载统计包
def mcor_test(X): #相关系数矩阵检验
p=X.shape[1];p
sp=np.ones([p, p]).astype(str)
for i in range(0,p):
for j in range(i,p):
P=st.pearsonr(X.iloc[:,i],X.iloc[:,j])[1]
if P>0.05: sp[i,j]=' '
if(P>0.01 and P<=0.05): sp[i,j]='*'
if(P>0.001 and P<=0.01): sp[i,j]='**'
if(P<=0.001): sp[i,j]='***'
r=st.pearsonr(X.iloc[:,i],X.iloc[:,j])[0]
sp[j,i]=round(r,4)
if(i==j):sp[i,j]='------'
print(pd.DataFrame(sp,index=X.columns,columns=X.columns))
print("\n下三角为相关系数,上三角为检验p值 * p<0.05 ** p<0.05 *** p<0.001")
In [49]:
Copied!
mcor_test(d94) #多元数据相关系数检验
mcor_test(d94) #多元数据相关系数检验
y x1 x2 x3 x4 y ------ *** *** *** *** x1 0.9978 ------ *** *** *** x2 0.9996 0.9984 ------ *** *** x3 0.9708 0.9769 0.976 ------ *** x4 0.6521 0.6911 0.6641 0.7348 ------ 下三角为相关系数,上三角为检验p值 * p<0.05 ** p<0.05 *** p<0.001
9.3.2 多元线性回归模型的建立¶
In [52]:
Copied!
fm=ols('y~x1+x2+x3+x4',data=d94).fit()
fm.params #模型参数
fm=ols('y~x1+x2+x3+x4',data=d94).fit()
fm.params #模型参数
Out[52]:
Intercept 28.8592 x1 0.0236 x2 1.1658 x3 -0.0452 x4 -0.0592 dtype: float64
In [54]:
Copied!
#from scipy import stats
#fm1_z=ols('y ~ x1+x2+x3+x4',data=d9_4.apply(stats.zscore)).fit()
#fm1_z.params #标准回归系数
#from scipy import stats
#fm1_z=ols('y ~ x1+x2+x3+x4',data=d9_4.apply(stats.zscore)).fit()
#fm1_z.params #标准回归系数
9.3.3 多元线性回归模型的检验¶
In [57]:
Copied!
print(fm.summary()) #多元线性回归系数t检验
print(fm.summary()) #多元线性回归系数t检验
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 1.000
Model: OLS Adj. R-squared: 1.000
Method: Least Squares F-statistic: 2.527e+04
Date: Tue, 13 May 2025 Prob (F-statistic): 1.60e-61
Time: 20:35:21 Log-Likelihood: -154.70
No. Observations: 41 AIC: 319.4
Df Residuals: 36 BIC: 328.0
Df Model: 4
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept 28.8592 15.544 1.857 0.072 -2.666 60.385
x1 0.0236 0.017 1.393 0.172 -0.011 0.058
x2 1.1658 0.096 12.084 0.000 0.970 1.361
x3 -0.0452 0.010 -4.642 0.000 -0.065 -0.025
x4 -0.0592 0.029 -2.032 0.050 -0.118 -0.000
==============================================================================
Omnibus: 19.046 Durbin-Watson: 1.007
Prob(Omnibus): 0.000 Jarque-Bera (JB): 79.387
Skew: 0.694 Prob(JB): 5.77e-18
Kurtosis: 9.674 Cond. No. 3.22e+04
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 3.22e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
In [59]:
Copied!
fm1=ols('y~x1',data=d94).fit();fm1.params
fm1=ols('y~x1',data=d94).fit();fm1.params
Out[59]:
Intercept -37.6734 x1 0.2161 dtype: float64
In [61]:
Copied!
fm2=ols('y~x1+x2',data=d94).fit();fm2.params
fm2=ols('y~x1+x2',data=d94).fit();fm2.params
Out[61]:
Intercept -6.7185 x1 -0.0169 x2 1.2819 dtype: float64
In [63]:
Copied!
fm3=ols('y~x1+x2+x3',data=d94).fit();fm3.params
fm3=ols('y~x1+x2+x3',data=d94).fit();fm3.params
Out[63]:
Intercept -2.1992 x1 0.0001 x2 1.3067 x3 -0.0561 dtype: float64
In [65]:
Copied!
fm4=ols('y~x1+x2+x3+x4',data=d94).fit();fm4.params
fm4=ols('y~x1+x2+x3+x4',data=d94).fit();fm4.params
Out[65]:
Intercept 28.8592 x1 0.0236 x2 1.1658 x3 -0.0452 x4 -0.0592 dtype: float64
In [67]:
Copied!
from statsmodels.iolib.summary2 import summary_col
summary_col([fm1,fm2,fm3,fm4])
from statsmodels.iolib.summary2 import summary_col
summary_col([fm1,fm2,fm3,fm4])
Out[67]:
| y I | y II | y III | y IIII | |
|---|---|---|---|---|
| Intercept | -37.6734 | -6.7185 | -2.1992 | 28.8592 |
| (7.6691) | (4.2058) | (2.9642) | (15.5444) | |
| x1 | 0.2161 | -0.0169 | 0.0001 | 0.0236 |
| (0.0023) | (0.0185) | (0.0130) | (0.0170) | |
| x2 | 1.2819 | 1.3067 | 1.1658 | |
| (0.1017) | (0.0699) | (0.0965) | ||
| x3 | -0.0561 | -0.0452 | ||
| (0.0085) | (0.0097) | |||
| x4 | -0.0592 | |||
| (0.0291) | ||||
| R-squared | 0.9955 | 0.9991 | 0.9996 | 0.9996 |
| R-squared Adj. | 0.9954 | 0.9991 | 0.9996 | 0.9996 |
Standard errors in parentheses.
9.3.4 复相关及模型的决定系数¶
In [70]:
Copied!
R2=fm.rsquared
print('模型的决定系数 R^2 = %5.4f'%R2)
R2=fm.rsquared
print('模型的决定系数 R^2 = %5.4f'%R2)
模型的决定系数 R^2 = 0.9996
In [72]:
Copied!
R=np.sqrt(R2);R
print('变量的复相关系数 R = %5.4f'%np.sqrt(R2))
R=np.sqrt(R2);R
print('变量的复相关系数 R = %5.4f'%np.sqrt(R2))
变量的复相关系数 R = 0.9998
案例9:中国宏观经济发展的多因素分析¶
In [75]:
Copied!
Case9=pd.read_excel('mvsCase.xlsx','Case9'); Case9
Case9=pd.read_excel('mvsCase.xlsx','Case9'); Case9
Out[75]:
| Y | X1 | X2 | X3 | X4 | X5 | X6 | |
|---|---|---|---|---|---|---|---|
| 0 | 40.78 | 5.38 | 4.55 | 18.00 | 20.14 | 8.57 | 2.81 |
| 1 | 45.75 | 5.72 | 5.70 | 21.40 | 23.37 | 9.11 | 3.96 |
| 2 | 49.57 | 6.30 | 7.35 | 23.50 | 26.28 | 9.61 | 5.24 |
| 3 | 54.26 | 7.00 | 7.71 | 25.70 | 28.67 | 12.00 | 6.75 |
| 4 | 60.79 | 7.76 | 8.60 | 28.49 | 32.21 | 14.30 | 8.93 |
| ... | ... | ... | ... | ... | ... | ... | ... |
| 35 | 6471.82 | 1191.75 | 2642.42 | 2718.96 | 2425.40 | 5120.21 | 4852.61 |
| 36 | 6991.09 | 1249.22 | 2455.03 | 3009.31 | 2659.80 | 5620.00 | 5460.78 |
| 37 | 7456.32 | 1303.61 | 2433.86 | 3323.16 | 2934.43 | 6064.66 | 5977.51 |
| 38 | 8152.60 | 1443.70 | 2780.99 | 3662.62 | 3179.64 | 6412.38 | 6437.68 |
| 39 | 8844.26 | 1564.03 | 3050.10 | 3809.87 | 3482.10 | 6456.75 | 7160.38 |
40 rows × 7 columns
In [77]:
Copied!
#Case9.describe()
#Case9.describe()
In [79]:
Copied!
mcor_test(Case9) #相关系数两两检验
mcor_test(Case9) #相关系数两两检验
Y X1 X2 X3 X4 X5 X6 Y ------ *** *** *** *** *** *** X1 0.9984 ------ *** *** *** *** *** X2 0.9709 0.9705 ------ *** *** *** *** X3 0.997 0.9955 0.9508 ------ *** *** *** X4 0.9986 0.9952 0.9609 0.9983 ------ *** *** X5 0.9914 0.993 0.9393 0.9967 0.9912 ------ *** X6 0.9984 0.9966 0.9592 0.9989 0.9989 0.9939 ------ 下三角为相关系数,上三角为检验p值 * p<0.05 ** p<0.05 *** p<0.001
In [81]:
Copied!
pd.plotting.scatter_matrix(Case9); #矩阵散点图
pd.plotting.scatter_matrix(Case9); #矩阵散点图
In [82]:
Copied!
from statsmodels.formula.api import ols
print(ols('Y~X1+X2+X3+X4+X5+X6',data=Case9).fit().summary())
from statsmodels.formula.api import ols
print(ols('Y~X1+X2+X3+X4+X5+X6',data=Case9).fit().summary())
OLS Regression Results
==============================================================================
Dep. Variable: Y R-squared: 1.000
Model: OLS Adj. R-squared: 1.000
Method: Least Squares F-statistic: 3.136e+04
Date: Tue, 13 May 2025 Prob (F-statistic): 1.71e-60
Time: 20:35:49 Log-Likelihood: -198.15
No. Observations: 40 AIC: 410.3
Df Residuals: 33 BIC: 422.1
Df Model: 6
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept 8.4152 13.202 0.637 0.528 -18.445 35.276
X1 1.5485 0.331 4.681 0.000 0.875 2.221
X2 0.2792 0.055 5.031 0.000 0.166 0.392
X3 0.2015 0.334 0.603 0.550 -0.478 0.881
X4 1.2407 0.262 4.732 0.000 0.707 1.774
X5 0.0263 0.071 0.368 0.715 -0.119 0.171
X6 0.0469 0.088 0.533 0.597 -0.132 0.226
==============================================================================
Omnibus: 19.518 Durbin-Watson: 0.758
Prob(Omnibus): 0.000 Jarque-Bera (JB): 27.179
Skew: 1.460 Prob(JB): 1.25e-06
Kurtosis: 5.790 Cond. No. 9.44e+03
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 9.44e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
In [85]:
Copied!
fm=ols('Y~X1+X2+X4',data=Case9).fit();
print(fm.summary())
fm=ols('Y~X1+X2+X4',data=Case9).fit();
print(fm.summary())
OLS Regression Results
==============================================================================
Dep. Variable: Y R-squared: 1.000
Model: OLS Adj. R-squared: 1.000
Method: Least Squares F-statistic: 6.357e+04
Date: Tue, 13 May 2025 Prob (F-statistic): 4.51e-67
Time: 20:35:49 Log-Likelihood: -199.62
No. Observations: 40 AIC: 407.2
Df Residuals: 36 BIC: 414.0
Df Model: 3
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept 0.1393 9.924 0.014 0.989 -19.987 20.266
X1 2.0071 0.151 13.321 0.000 1.701 2.313
X2 0.2053 0.025 8.284 0.000 0.155 0.256
X4 1.4735 0.063 23.313 0.000 1.345 1.602
==============================================================================
Omnibus: 17.237 Durbin-Watson: 0.837
Prob(Omnibus): 0.000 Jarque-Bera (JB): 21.803
Skew: 1.349 Prob(JB): 1.84e-05
Kurtosis: 5.408 Cond. No. 3.24e+03
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 3.24e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
In [87]:
Copied!
plt.figure(figsize=(7,5))
plt.plot(Case9.Y,'o',Case9.index,fm.fittedvalues,'-');
plt.figure(figsize=(7,5))
plt.plot(Case9.Y,'o',Case9.index,fm.fittedvalues,'-');
In [ ]:
Copied!