SciPy - I need an example of use of linalg.lstsq()

Robert Kern robert.kern at gmail.com
Wed May 10 01:22:27 EDT 2006


I. Myself wrote:
> And it has to run on Windows, so it can't use xplt.

Huh?

A. xplt runs on Windows, too.
B. xplt has nothing to do with linalg.lstsq().
C. xplt has been removed from scipy.

> I would prefer that it use the simplest multi-dimensional model, z = k + 
> a*x1 + b*x2 + c*x3 + d*x4

In [1]: import numpy as np

In [2]: np.linalg.lstsq?
Type:           function
Base Class:     <type 'function'>
String Form:    <function lstsq at 0x6d3f30>
Namespace:      Interactive
File:
/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/numpy-0.9.7.2476-py2.4-macosx-10.4-ppc.egg/numpy/linalg/linalg.py
Definition:     np.linalg.lstsq(a, b, rcond=1e-10)
Docstring:
    returns x,resids,rank,s
    where x minimizes 2-norm(|b - Ax|)
          resids is the sum square residuals
          rank is the rank of A
          s is the rank of the singular values of A in descending order

    If b is a matrix then x is also a matrix with corresponding columns.
    If the rank of A is less than the number of columns of A or greater than
    the number of rows, then residuals will be returned as an empty array
    otherwise resids = sum((b-dot(A,x)**2).
    Singular values less than s[0]*rcond are treated as zero.


In [3]: z = np.rand(10)

In [4]: x1 = np.rand(10)

In [5]: x2 = np.rand(10)

In [6]: x3 = np.rand(10)

In [7]: x4 = np.rand(10)

In [8]: A = np.column_stack([x1, x2, x3, x4, np.ones(10, float)])

In [9]: A
Out[9]:
array([[ 0.07257264,  0.36544251,  0.68467294,  0.33813333,  1.        ],
       [ 0.09520828,  0.27102091,  0.04673061,  0.12905473,  1.        ],
       [ 0.839834  ,  0.46010114,  0.3949568 ,  0.38983012,  1.        ],
       [ 0.49776387,  0.70666191,  0.85005579,  0.47738743,  1.        ],
       [ 0.25457977,  0.93335912,  0.88441593,  0.05255062,  1.        ],
       [ 0.85982216,  0.97920853,  0.27991214,  0.94230651,  1.        ],
       [ 0.03224487,  0.1275237 ,  0.66943552,  0.320765  ,  1.        ],
       [ 0.86807363,  0.63800103,  0.67153924,  0.69125023,  1.        ],
       [ 0.26571213,  0.68845408,  0.06478114,  0.03657494,  1.        ],
       [ 0.46615143,  0.99464106,  0.9303421 ,  0.61363703,  1.        ]])

In [10]: np.linalg.lstsq(A, z)
Out[10]:
(array([-0.32421087, -0.23330787,  0.13369118, -0.28334431,  0.84010014]),
 array([ 0.22958042]),
 5,
 array([ 4.59505886,  1.1181838 ,  0.85704672,  0.70211311,  0.4420187 ]))


If you have more scipy questions, you will probably want to ask on the
scipy-user list:

  http://www.scipy.org/Mailing_Lists

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list