Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parameters constraint in numpy lstsq

Tags:

python

numpy

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}
like image 700
rudy Avatar asked Aug 08 '16 10:08

rudy


People also ask

What does Numpy Linalg Lstsq do?

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.

What does NP Linalg Lstsq return?

lstsq. Return the least-squares solution to a linear matrix equation.

What is linalg lstsq in NumPy?

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.

How to solve least squares problems with side constraints in Python?

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.

Why does NumPy raise linalgerror when matrix is not square?

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.

How do you solve a line equation with lstsq?

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.]])


Video Answer


1 Answers

Non-negative least squares is implemented in scipy.optimize.nnls.

from scipy.optimize import nnls

solution = nnls(a, b)[0]
like image 185
A. Garcia-Raboso Avatar answered Sep 18 '22 00:09

A. Garcia-Raboso