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!
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.
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).
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.
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"
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