gpt4 book ai didi

类似于 R 的 Python 线性回归诊断图

转载 作者:行者123 更新时间:2023-12-04 16:08:55 27 4
gpt4 key购买 nike

我正在尝试在 Python 中获取线性回归的诊断图,我想知道是否有一种快速的方法可以做到这一点。

在 R 中,您可以使用下面的代码片段,该代码片段将为您提供残差与拟合图、正常 Q-Q​​ 图、比例位置、残差与杠杆图。

m1 <- lm(cost~ distance, data = df1)
summary(m1)
plot(m1)

在python中有没有一种快速的方法来做到这一点?

有一篇很棒的博客文章描述了如何使用 Python 代码获得与 R 相同的绘图,但它需要相当多的代码(至少与 R 方法相比)。链接: https://underthecurve.github.io/jekyll/update/2016/07/01/one-regression-six-ways.html#Python

最佳答案

我更喜欢将所有内容存储在 pandas 中并用 DataFrame.plot() 绘图只要有可能:

from matplotlib import pyplot as plt
from pandas.core.frame import DataFrame
import scipy.stats as stats
import statsmodels.api as sm


def linear_regression(df: DataFrame) -> DataFrame:
"""Perform a univariate regression and store results in a new data frame.

Args:
df (DataFrame): orginal data set with x and y.

Returns:
DataFrame: another dataframe with raw data and results.
"""
mod = sm.OLS(endog=df['y'], exog=df['x']).fit()
influence = mod.get_influence()

res = df.copy()
res['resid'] = mod.resid
res['fittedvalues'] = mod.fittedvalues
res['resid_std'] = mod.resid_pearson
res['leverage'] = influence.hat_matrix_diag
return res


def plot_diagnosis(df: DataFrame):
fig, axes = plt.subplots(nrows=2, ncols=2)
plt.style.use('seaborn')

# Residual against fitted values.
df.plot.scatter(
x='fittedvalues', y='resid', ax=axes[0, 0]
)
axes[0, 0].axhline(y=0, color='grey', linestyle='dashed')
axes[0, 0].set_xlabel('Fitted Values')
axes[0, 0].set_ylabel('Residuals')
axes[0, 0].set_title('Residuals vs Fitted')

# qqplot
sm.qqplot(
df['resid'], dist=stats.t, fit=True, line='45',
ax=axes[0, 1], c='#4C72B0'
)
axes[0, 1].set_title('Normal Q-Q')

# The scale-location plot.
df.plot.scatter(
x='fittedvalues', y='resid_std', ax=axes[1, 0]
)
axes[1, 0].axhline(y=0, color='grey', linestyle='dashed')
axes[1, 0].set_xlabel('Fitted values')
axes[1, 0].set_ylabel('Sqrt(|standardized residuals|)')
axes[1, 0].set_title('Scale-Location')

# Standardized residuals vs. leverage
df.plot.scatter(
x='leverage', y='resid_std', ax=axes[1, 1]
)
axes[1, 1].axhline(y=0, color='grey', linestyle='dashed')
axes[1, 1].set_xlabel('Leverage')
axes[1, 1].set_ylabel('Sqrt(|standardized residuals|)')
axes[1, 1].set_title('Residuals vs Leverage')

plt.tight_layout()
plt.show()
仍然缺少许多功能,但它提供了一个良好的开端。我在这里学习了如何提取影响力统计信息, Access standardized residuals, cook's values, hatvalues (leverage) etc. easily in Python?
enter image description here
顺便说一句,有一个包裹, dynobo/lmdiag ,具有所有功能。

关于类似于 R 的 Python 线性回归诊断图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46607831/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com