Python code of WLS
时间: 2023-11-05 10:07:52 浏览: 125
WLS (Weighted Least Squares) is a method used to estimate the parameters of a linear regression model when the errors are heteroscedastic (i.e., the variance of the errors is not constant). Here is an example Python code of WLS:
```python
import numpy as np
import statsmodels.api as sm
# Generate some data
x = np.arange(10)
y = 2*x + 5 + np.random.normal(0, 1, 10) # Heteroscedastic errors
# Fit a linear regression model using WLS
weights = 1 / np.arange(1, 11) # Weights are inversely proportional to x
X = sm.add_constant(x)
model = sm.WLS(y, X, weights=weights)
results = model.fit()
# Print the results
print(results.summary())
```
In this example, we generate some data with heteroscedastic errors and fit a linear regression model using WLS. The weights are chosen to be inversely proportional to x (i.e., higher weights are assigned to smaller values of x), which is a common choice in practice. The `sm.WLS` function from the `statsmodels` library is used to perform the WLS estimation, and the results are printed using the `summary` method of the `results` object.
阅读全文