statsmodels中wls的例子是错误的吗?

2024-05-28 19:29:25 发布

您现在位置:Python中文网/ 问答频道 /正文

wls示例的完整代码可以在这里找到:Weighted Least Squares,为了方便起见,我将复制它。在

In [1]: from __future__ import print_function
   ...: import numpy as np
   ...: from scipy import stats
   ...: import statsmodels.api as sm
   ...: import matplotlib.pyplot as plt
   ...: from statsmodels.sandbox.regression.predstd import wls_prediction_std
   ...: from statsmodels.iolib.table import (SimpleTable, default_txt_fmt)
   ...: np.random.seed(1024)
   ...: 

In [2]: nsample = 50
   ...: x = np.linspace(0, 20, nsample)
   ...: X = np.column_stack((x, (x - 5)**2))
   ...: X = sm.add_constant(X)
   ...: beta = [5., 0.5, -0.01]
   ...: sig = 0.5
   ...: w = np.ones(nsample)
   ...: w[nsample * 6 // 10:] = 3
   ...: y_true = np.dot(X, beta)
   ...: e = np.random.normal(size=nsample)
   ...: y = y_true + sig * w * e
   ...: X = X[:,[0,1]]
   ...: 

In [3]: 
   ...: mod_wls = sm.WLS(y, X, weights=1./w)
   ...: res_wls = mod_wls.fit()
   ...: print(res_wls.summary())
   ...: 

让我困惑的是这行代码:

^{pr2}$

根据the docs of WLS

The weights are presumed to be (proportional to) the inverse of the variance of the observations. That is, if the variables are to be transformed by 1/sqrt(W) you must supply weights = 1/W.

因此,wls模型不应该通过以下方式构建:

mod_wls = sm.WLS(y, X, weights=1./w ** 2)

我错过什么了吗?在


Tags: ofthetoinfromimportmodas

热门问题