Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle an np.RankWarning in numpy?

I will try to phrase this as best as I can, though I am novice and beg for your lenience:

I am using the code below to find the polynomial that best fits some data that I read dynamically from a physical temperature sensor:

coefficients = numpy.polyfit(x, y, 2)
polynomial = numpy.poly1d(self.coefficients)

#and then I using matpltlib to plot
matplotlib.pyplot.plot(self.x, self.y, 'o')

From time to time I will not receive enough data and as a result I will get an error:

"RankWarning: Polyfit may be poorly conditioned warnings.warn(msg, RankWarning)"

Fair enough. Here is what I need to do (and cannot): If I get the exception from the polyfit, then I do not want to attempt to plot. In other words I need to take action when I get the exception, and not merely ignore the exception. Some code I found in the numpy documentation merely ignores the exception

import warnings
warnings.simplefilter('ignore', np.RankWarning)

I have tried using try except but that does not work in this case (I have a rudimentary understanding of the different kinds of exceptions, though I plan to read about more soon).

Your suggestions appreciated!

like image 525
andgeo Avatar asked Jan 21 '14 08:01

andgeo


People also ask

How do you fit a polynomial to data in Python?

To get the least-squares fit of a polynomial to data, use the polynomial. polyfit() in Python Numpy. The method returns the Polynomial coefficients ordered from low to high. If y was 2-D, the coefficients in column k of coef represent the polynomial fit to the data in y's k-th column.

What is Numpy Polyfit?

Introduction to NumPy polyfit. In python, Numpy polyfit() is a method that fits the data within a polynomial function. That is, it least squares the function polynomial fit. For example, a polynomial p(X) of deg degree fits the coordinate points (X, Y).

What does NP Polyfit return?

The np. polyfit() method takes a few parameters and returns a vector of coefficients p that minimizes the squared error in the order deg, deg-1, … 0. It least squares the polynomial fit.


1 Answers

import numpy as np
import warnings
x = [1]
y = [2]

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        coefficients = np.polyfit(x, y, 2)
    except np.RankWarning:
        print "not enought data"
like image 101
HYRY Avatar answered Sep 23 '22 05:09

HYRY