【发布时间】:2011-05-16 20:18:03
【问题描述】:
我的文件中有 10 个 x 和 y 值。
有什么方法可以推断图表,即使其成为连续函数并增加其范围以适应 matplotlib 中的其他 x 值??
如果有人能告诉我是否有任何其他软件可以使用,我什至会很感激。我基本上希望这 10 个值近似为一个连续函数,这样我就可以知道某个随机 x 点的 y 值。
【问题讨论】:
标签: python numpy matplotlib
我的文件中有 10 个 x 和 y 值。
有什么方法可以推断图表,即使其成为连续函数并增加其范围以适应 matplotlib 中的其他 x 值??
如果有人能告诉我是否有任何其他软件可以使用,我什至会很感激。我基本上希望这 10 个值近似为一个连续函数,这样我就可以知道某个随机 x 点的 y 值。
【问题讨论】:
标签: python numpy matplotlib
下面我使用Scipy,但相同函数(polyval和polyfit)也在NumPy; NumPy 是一个 Matplotlib 依赖项,因此如果您没有安装 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()
【讨论】:
您想要的大部分内容都可以在这里找到: http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html
但不要外推,至少在你完全确定自己知道自己在做什么之前。
【讨论】:
如果您使用SciPy(科学Python),您可以尝试scipy.interp1d。有关示例,请参见 manual。
否则,任何像样的电子表格软件都应该能够进行样条插值并为您提供漂亮的平滑图形。
不过,请注意外推。如果您的数据没有一个好的模型,当您在输入范围之外进行推断时,您可能会得到完全不相关的数据。
示例(编辑):
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')
您现在可以在任意点 x 计算函数 f(x)。例如print f(2.5) 将返回 x=2.5 的插值。
【讨论】: