I'm fitting a set of data with numpy.lstsq()
:
numpy.linalg.lstsq(a,b)[0]
returns something like:
array([ -0.02179386, 0.08898451, -0.17298247, 0.89314904])
Note the fitting solution is a mix of positive and negative float.
Unfortunately, in my physical model, the fitting solutions represent a mass: consequently I'd like to force lstsq()
to return a set of positive values as a solution of the fitting. Is it possible to do this?
i.e.
solution = {a_1, ... a_i, ... a_N} with a_i > 0 for i = {1, ..., N}
The numpy linalg lstsq() function returns the least-squares solution to a linear matrix equation. For example, it solves the equation ax = b by computing a vector x that minimizes the Euclidean 2-norm || b – ax ||^2.
lstsq. Return the least-squares solution to a linear matrix equation.
numpy.linalg.lstsq linalg.lstsq(a, b, rcond='warn')[source] Return the least-squares solution to a linear matrix equation. Computes the vector xthat approximatively solves the equation a @ x = b.
In general, least squares problems with side constraints can be solved as a QP (Quadratic Programming) problem. QP solvers for Python are readily available. The description is wordy and not very precise. Hence I am not sure if this is the correct mathematical model, but this is my interpretation: r can be interpreted as residuals.
Here, numpy raised a LinAlgError because the matrix was not square, and therefore the inverse is poorly defined. numpy actually does some other little bits behind the scenes (see LAPACK), but this is close enough for discussion here. The number of columns in coefficients is 6, and the number of rows is 32. The number of rows in maxPoints is 32.
We can rewrite the line equation as y = Ap, where A = [ [x 1]] and p = [ [m], [c]]. Now use lstsq to solve for p: >>> A = np.vstack( [x, np.ones(len(x))]).T >>> A array ( [ [ 0., 1.], [ 1., 1.], [ 2., 1.], [ 3., 1.]])
Non-negative least squares is implemented in scipy.optimize.nnls
.
from scipy.optimize import nnls
solution = nnls(a, b)[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With