返回介绍

Calculation of Cook’s distance

发布于 2025-02-25 23:43:56 字数 1341 浏览 0 评论 0 收藏 0

Cook’s distance is used to estimate the influence of a data point when performing least squares regression analysis. It is one of the standard plots for linear regression in R and provides another example of the applicationof leave-one-out resampling.

\[D_i = \frac{\sum_{j=1}^n (\hat Y_j - \hat Y_{j(i)})^2}{p\ \text{MSE}}\]

The calculation of Cook’s distance involves the fitting of \(n\) regression models, so we want to do this as efficiently as possible.

def cook_dist(X, y, model):
    """Vectorized version of Cook's distance."""
    n = len(X)
    fitted = model(y, X).fit()
    yhat = fitted.predict(X)
    p = len(fitted.params)
    mse = np.sum((yhat - y)**2.0)/n
    denom = p*mse
    idx = np.arange(n)
    return np.array([np.sum((yhat - model(y[idx!=i], X[idx!=i]).fit().predict(X))**2.0) for i in range(n)])/denom
import statsmodels.api as sm
# create data set with outliers
nobs = 100
X = np.random.random((nobs, 2))
X = sm.add_constant(X)
beta = [1, .1, .5]
e = np.random.random(nobs)
y = np.dot(X, beta) + e
y[[7, 29, 78]] *= 3
# use Cook's distance to identify outliers
model = sm.OLS
d = cook_dist(X, y, model)
plt.stem(d);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文