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]

Thanks by advance,

  • 1
    Have you looked at this link: stackoverflow.com/questions/19624997/… – xnx Nov 25 '14 at 14:56
  • Yes; I tried: B=numpy.dot(B,W) before solving, but I have a message: numpy.linalg.linalg.LinAlgError: 0-dimensional array given. Array must be two-dimensional – Eric H. Nov 25 '14 at 15:03
  • 2
    If you take the dot product of two one-dimensional arrays you will get a scalar. Perhaps you mean to simply multiply the elements of B by those of W? Better to use numpy arrays rather than Python lists here. – xnx Nov 25 '14 at 15:08

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)
  • 1
    Thanks. I don't know well numpy, and have to realize that W[:,np.newaxis] (or W[:,None]) gives a diagonal matrix. I.e. array([[1],[2],[3],[4],[5]]) means a 5x5 diagonal matrix with these values on the diagonal. – Eric H. Nov 26 '14 at 7:48
  • 1
    (Is it ? Because the result Aw is a 5x4 array, so that's the only explanation) – Eric H. Nov 26 '14 at 7:55
  • 1
    Sorry, I was confused by the * operator (I was not used to arrays). It is not a matrix product, but term to term. – Eric H. Nov 26 '14 at 9:08
  • 1
    That's right, NumPy arrays use * as the elementwise multiplication operator. You need to turn W into a column array to broadcast this multiplication correctly over A. There is also a NumPY matrix object, but it's more trouble than it's worth (IMO). – xnx Nov 26 '14 at 14:32
up vote 4 down vote accepted

I found another approach (using W as a diagonal matrix, and matricial products) :

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]
W = np.sqrt(np.diag(W))
Aw = np.dot(W,A)
Bw = np.dot(B,W)
X = np.linalg.lstsq(Aw, Bw)

Same values and same results.

  • 1
    the matrix product is more expensive than the element-wise product of @xnx's suggestion – DomTomCat Apr 3 '17 at 11:44
  • 1
    might be more computationally expensive but this is way more clear to read. +1 for code clarity with linear algebra – D Adams May 14 '17 at 23:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.