import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.formula.api as smf
import pandas as pd
from statsmodels.formula.api import ols
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def Corr_heatmap(data):
# import matplotlib.pyplot as plt
# import seaborn as sns
#相关性分析
print(data.corr())
#画出热力图
plt.figure(figsize=(7,5),dpi=128)
sns.heatmap(data.corr().round(2), cmap='coolwarm', annot=True, annot_kws={"size": 10})
plt.savefig('相关系数热力图.jpg')
plt.show()
def VIF_calculate(data, y_name):
# import statsmodels.formula.api as smf
# import pandas as pd
x_cols = data.columns.to_list()
x_cols.remove(y_name)
def vif(df_exog, exog_name):
exog_use = list(df_exog.columns)
exog_use.remove(exog_name)
model = smf.ols(f"{exog_name}~{'+'.join(list(exog_use))}", data=df_exog).fit()
return 1. / (1. - model.rsquared)
df_vif = pd.DataFrame()
for x in x_cols:
df_vif.loc['VIF', x] = vif(data[x_cols], x)
df_vif.loc['tolerance'] = 1 / df_vif.loc['VIF']
df_vif = df_vif.T.sort_values('VIF', ascending=False)
df_vif.loc['mean_vif'] = df_vif.mean()
# from statsmodels.formula.api import ols
def vif(data, col_i):
"""
df: 整份数据
col_i:被检测的列名
"""
cols = list(data.columns)
cols.remove(col_i)
cols_noti = cols
formula = col_i + '~' + '+'.join(cols_noti)
r2 = ols(formula, data).fit().rsquared
# 其实就是多元线性回归建模步骤,只是取出了参数 R 平方而已
test = 1. / (1. - r2)
return test
print('vif检验结果')
print(' 变量 vif检验值')
vif_value = []
for i in data:
print(i.center(7) + ' ', str(vif(data=data, col_i=i)))
vif_value.append(vif(data=data, col_i=i))
plt.bar([x for x in data], vif_value, color='teal')
plt.axhline(10, color='red', lw=2, label="参考线")
plt.title("VIF检验结果")
plt.xlabel("变量")
plt.ylabel("VIF_value")
plt.show()
return print(df_vif)
def Residuals_plot(predicts,residuals):
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.subplots(2, 2, figsize=(8, 8), dpi=128)
plt.subplot(221)
plt.scatter(predicts, residuals)
plt.xlabel('Fitted Value')
plt.ylabel('Residual')
plt.title('(a)Residuals vs Fitted Plot', fontsize=15)
plt.axhline(0, ls='--')
ax2 = plt.subplot(222)
pplot = sm.ProbPlot(residuals, fit=True)
pplot.qqplot(line='r', ax=ax2, xlabel='Theoretical Quantiles', ylabel='Sample Quantiles')
ax2.set_title('(b)Normal Q-Q Plot', fontsize=15)
#创建一个序列来表示观测序号:
obs = np.arange(1, len(residuals) + 1)
#绘制scale-location图
ax3 = plt.subplot(223)
ax3.scatter(np.sqrt(obs), np.abs(residuals))
ax3.set_xlabel("√Observation Number")
ax3.set_ylabel("|Residuals|")
ax3.set_title("(c)Scale-Location Plot")
#计算库克距离并绘制库克距离图:
model = sm.OLS(residuals, sm.add_constant(obs)).fit() # 应用OLS回归模型
influence = model.get_influence()
cooks_dist = influence.cooks_distance[0]
ax4=plt.subplot(224)
ax4.scatter(obs, cooks_dist)
ax4.axhline(y=4*cooks_dist.mean(), linestyle='dashed')
ax4.set_xlabel("Observation")
ax4.set_ylabel("Cook's Distance")
ax4.set_title("(d)Cook's Distance Plot")
plt.tight_layout()
plt.show()
评论区