我想将一个函数拟合到给定的数据集,如果不满足条件,则扩展该函数并重复该过程-类似于增加泰勒级数的最高阶。我的问题是我不知道如何扩展这个函数。这个函数应该是这样的
def func(x, a0,a1,a2,...)
return (a0 * H0 + a1 * H1 + a2 * H2 + ...) (x)
H0(x),H1(x),H2(x),。。。是已知的函数。我希望这个方法使用20-1000个函数H0,H1,。。。所以我必须找到一种方法,不去定义每个参数a0,a1,a2,。。。用手
我的想法是用最大数量的参数定义函数,然后在循环中操作它(以某种方式减少参数数量,然后随着每次迭代增加参数数量)
# choose N: an arbitrary number of parameters
# create N-many functions H0, H1, ... HN-1 -> put them into an numpy array HArray
def func(x, parameters): # somehow reduce the number of parameters to N
# convert parameters into numpy array -> parameterArray
result = parameterArray * HArray (x) # (a * H0 + b * H1 + c * H2 + ...) (x)
return result
# fit the function to a given dataset
作为完整代码
import numpy as np
from scipy.optimize import curve_fit
x = np.linspace(0,2*np.pi,num=10000) # xdata
y = np.sin(x) # ydata
error = 0.0001 # fit condition
K = 1000
for N in range(K):
def func(x, parameters): # somehow reduce the number of parameters to N
parameterArray = np.array([p for p in parameters])
HArray = np.array([x**i for i in range(N)]) # a polynomial as example
return parameterArray * HArray (x)
popt, pcov = curve_fit(func, x, y)
stdDev = np.sqrt(np.diag(pcov))
if stdDev < error: break
为了使曲线拟合工作,函数需要适当数量的参数。我还想在拟合时固定最后的K-N参数,但我也不知道怎么做
也就是说,如果我做对了,线性拟合。因此,不需要
curve_fit
。最简单的方法是:为了避免矩阵求逆等问题,可以使用矩阵分解等方法使其更复杂一些,但主要思想保持不变。如果输入函数需要附加参数,则可能需要使用
lambda
函数和/或相应地扩展代码编辑1
达到非常高的阶数会导致矩阵求逆或浮点精度问题。我们可以通过使用
mpmath
来解决这个问题 请注意,numpy
不再使用,现在需要以更手动的方式进行一些数据处理编辑2
事实上,numpy对此有一个内置机制。我不确定它是如何详细完成的,因为它最终会从库中调用函数,但我猜它使用SVD。QR分解仍然有助于获得协方差矩阵
编辑3
这将是仅使用QR分解的解决方案。在我的例子中,它可以轻松地工作到订单20(重新缩放)
相关问题 更多 >
编程相关推荐