2010-11-28 34 views
5

J'ai 10 valeurs de x et y dans mon fichier.Extrapolation à partir de données tracées en utilisant matplotlib

Existe-t-il un moyen que je peux extrapoler le graphique c'est-à-dire le rendre dans une fonction continue et augmenter sa gamme pour d'autres valeurs x dans matplotlib ??

Je serais même reconnaissant si quelqu'un peut me dire s'il y a un autre logiciel que je peux utiliser. Je veux fondamentalement que ces 10 valeurs soient approchées d'une fonction continue afin que je puisse connaître la valeur y à un certain point x aléatoire.

Répondre

12

ci-dessous i utiliser Scipy, mais les mêmes fonctions (Polyval et polyfit) sont également en NumPy; NumPy est une dépendance Matplotlib donc vous pouvez importer ces deux fonctions à partir de là si vous n'avez pas installé 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

5

Si vous utilisez SciPy (Scientific Python), vous pouvez essayer scipy.interp1d. Voir le manual pour un exemple. Sinon, tout logiciel de tableur décent devrait être en mesure d'effectuer une interpolation de spline et de vous donner un bon graphe.

Attention cependant à l'extrapolation . Si vous ne disposez pas d'un bon modèle pour vos données, vous pouvez obtenir des données complètement différentes lorsque vous extrapolez en dehors de votre plage d'entrée.

Exemple (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') 

Vous pouvez maintenant calculer la fonction f(x) à tout moment x. Par exemple, print f(2.5) renverra la valeur interpolée pour x = 2,5.