Fit weighted least squares in closed form
Why it matters Reward models and calibration fits often weight examples by confidence or by how many raters agreed.
Some rows are more trustworthy than others. Weighted least squares minimises sum_i s_i (y_i - x_i . w)^2 with a weight s_i per row.
Write wls_fit(X, y, s). X is (n, d), y is (n,), s is (n,) positive weights. Return w of shape (d,) solving (X^T S X) w = X^T S y, where S = diag(s). Do not add an intercept column yourself.
def wls_fit(X, y, s)Example
X = [[1, 0], [1, 1], [1, 2]], y = [1, 2, 4], s = [1, 1, 1] gives w close to [0.8333, 1.5].
Understand the idea
Ordinary least squares treats every row as equally trustworthy. Weighted least squares gives each row its own weight, so reliable rows pull the fit harder. You minimise sum of s_i * (y_i - x_i . w)^2, and the solution comes from weighted normal equations. Worked example: fit a single constant, X = [[1], [1]], y = [2, 5], s = [2, 1]. X^T S X = 2 + 1 = 3. X^T S y = 2 * 2 + 1 * 5 = 9. w = 9 / 3 = 3, a weighted average that sits closer to 2 because that row counts double. With equal weights the answer would be 3.5. Rule: solve (X^T S X) w = X^T S y with S = diag(s). You do not need the n by n matrix: multiply each row of X by its weight (broadcast s as a column), then X^T times that gives X^T S X, and X^T times s * y gives the right side. Both sides must be weighted; using plain X^T y on the right is the classic slip. Used when rows have different noise levels or represent different numbers of events.
Shapes and data flow
X (n, d) * s[:, None] -> (n, d) X^T (n, d) -> (d, d) normal matrix, X^T S y -> (d,)