Extrapolation from data plotted using matplotlib

I have 10 x and y values ​​in my file.

Is there a way that I can extrapolate the graph, that is, turn it into a continuous function and increase its range for other x values ​​in matplotlib ??

I would even be grateful if someone would tell me if there is other software that I can use. I basically want these 10 values ​​to approach a continuous function so that I can know the value of y at some random point x.

+5
source share
3 answers

I use Scipy below, but the same functions (polyval and polyfit) are also in NumPy; NumPy is a Matplotlib dependency, so you can import these two functions from there if you don't have SciPy.

import numpy as NP
from scipy import polyval, polyfit
from matplotlib import pyplot as PLT

n=10   # 10 data points
# make up some data
x = NP.linspace(0, 1, n)
y = 7*x**2 - 5*x + 3
# add some noise 
noise = NP.random.normal(.5, .3, 10)
y += noise

# the shape of the data suggests a 2d polynomial, so begin there
# a, b, c are the polynomial coefficients: ax^2 + bx + c
a, b, c = polyfit(x, y, 2)
y_pred = polyval([a, b, c], x)    # y_pred refers to predicted values of y

# how good is the fit?
# calculate MSE:
MSE = NP.sqrt( NP.sum((y_pred-y)**2)/10 )
# MSE = .2

# now use the model polynomial to generate y values based on x values outside 
# the range of the original data:
x_out = NP.linspace(0, 2, 20)   # choose 20 points, 10 in, 10 outside original range
y_pred = polyval([a, b, c], x_out)

# now plot the original data points and the polynomial fit through them
fig = PLT.figure()
ax1 = fig.add_subplot(111)

ax1.plot(x, y, 'g.', x_out, y_pred, 'b-' )

PLT.show()

alt text

+12
source

If you are using SciPy(Scientific Python), you can try scipy.interp1d. See the manual for an example.

Otherwise, any decent spreadsheet software should be able to do spline interpolation and give a good smooth graph.

Beware of extrapolation. If you do not have a good model for your data, you can get completely unrelated data by extrapolating outside your input range.

Example (EDIT):

from scipy.interpolate import interp1d

# the available data points
x = [1, 2, 3]
y = [10, 20, 30]

# return a function f, such that f(x) is the interpolated value at 'x'
f = interp1d(x, y, kind='cubic')

f(x) x. , print f(2.5) x = 2.5.

+5

Most of all you can find here: http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html

But do not extrapolate, at least until you are sure that you know what you are doing.

0
source

All Articles