我的文件中有10个x和y值.
有没有什么方法可以推断图形,即将它变成一个连续的函数,并增加matplotlib中其他x值的范围?
如果有人能告诉我是否还有其他可以使用的软件,我甚至会感激不尽.我基本上希望这10个值近似为连续函数,以便我可以知道某个随机x点的y值.
dou*_*oug 12
下面我使用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()
Run Code Online (Sandbox Code Playgroud)

如果您正在使用SciPy(Scientific Python),您可以尝试scipy.interp1d.有关示例,请参见手册.
否则,任何体面的电子表格软件都应该能够进行样条插值,并为您提供一个漂亮的平滑图形.
但要注意外推.如果您的数据没有良好的模型,则在输入范围之外进行外推时可能会得到完全不相关的数据.
示例(编辑):
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')
Run Code Online (Sandbox Code Playgroud)
您现在可以计算功能f(x)的任何一点x.例如,print f(2.5)将返回x = 2.5的插值.
| 归档时间: |
|
| 查看次数: |
10349 次 |
| 最近记录: |