How to use least squares with weight matrix?

Eric H. picture Eric H. · Nov 25, 2014 · Viewed 12.1k times · Source

I know how to solve A.X = B by least squares using Python:

Example:

A=[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,0,0]]
B=[1,1,1,1,1]
X=numpy.linalg.lstsq(A, B)
print X[0]
# [  5.00000000e-01   5.00000000e-01  -1.66533454e-16  -1.11022302e-16]

But what about solving this same equation with a weight matrix not being Identity:

A.X = B (W)

Example:

A=[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,0,0]]
B=[1,1,1,1,1]
W=[1,2,3,4,5]

Answer

xnx picture xnx · Nov 25, 2014

I don't know how you have defined your weights, but you could try this if appropriate:

import numpy as np
A=np.array([[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,0,0]])
B = np.array([1,1,1,1,1])
W = np.array([1,2,3,4,5])
Aw = A * np.sqrt(W[:,np.newaxis])
Bw = B * np.sqrt(W)
X = np.linalg.lstsq(Aw, Bw)