Fit weighted least squares from known error standard deviations using inverse-variance weights
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `wls_params_from_sigma(X, y, sigma)` that fits a weighted least squares (WLS) regression of `y` on `X`. `X` is a raw `(n, p)` matrix without an intercept column, and `sigma` is a 1-D array of length `n` holding the known error standard deviation of each observation. Convert `sigma` into inverse-variance weights before fitting.
The function must:
- Pass `weights = 1.0 / sigma**2` to the model (not `1/sigma`, `sigma`, or `sigma**2`).
- Prepend an intercept column with `sm.add_constant`.
- Return a 1-D `np.ndarray` of shape `(p+1,)` ordered `[intercept, b1, ..., bp]`.
For example:
```python
X = np.array([[0.0], [1.0], [2.0]]) # shape (3, 1)
y = np.array([0.0, 2.0, 1.0])
sigma = np.array([1.0, 0.5, 1.0]) # standard deviations
beta = wls_params_from_sigma(X, y, sigma)
# beta -> [1.0, 0.5] ([intercept, b1])
```
The middle observation has the smallest standard deviation, so it gets the largest weight and the line moves up toward it. Plain OLS on the same points returns `[0.5, 0.5]`.
```hint Check the intercept
Make sure the returned array always has p + 1 entries. Look at what `sm.add_constant` does by default when `X` already contains a column with the same value in every row.
```
```hint Why the square
Write out the WLS objective with your weights and divide each residual by its own standard deviation. Compare the result with the objective you get from the other candidate weights.
```
### Constraints & Assumptions
- `X` has shape `(n, p)` with no intercept column; `y` and `sigma` have length `n`.
- `sigma` holds known, strictly positive standard deviations, not variances.
- NumPy and `statsmodels.api as sm` are available.
### What a Strong Answer Covers
- The conversion from standard deviations to inverse-variance weights, and why the power is 2.
- An intercept prepended as the first column, with the `(p+1,)` shape guaranteed.
- A plain 1-D NumPy array in the order `[intercept, b1, ..., bp]`.
- What wrong weights do to the bias and the variance of the estimates.
- Edge cases such as zero or non-finite `sigma` and pandas inputs.
### Follow-up Questions
- Why is the weight the inverse of the variance and not the inverse of the standard deviation?
- How does WLS relate to OLS on transformed data?
- If the stated `sigma` values are correct only up to a common factor, does that change the coefficients or their standard errors?
Overview: Implement a weighted least squares fit in Python with statsmodels when each observation's error standard deviation is known, converting it into the right weights. It tests why the weights are inverse variances, how WLS matches OLS on rescaled data, and the edge cases that break the fit.