numpy的polyfit函数如何反向输出结果?

3

我使用了numpy的polyfit函数,用一个7阶多项式对两个数组x和y拟合得非常好。我的关系是这样的;

y(x) = p[0]* x^7 + p[1]*x^6 + p[2]*x^5 + p[3]*x^4 + p[4]*x^3 + p[5]*x^2 + p[6]*x^1 + p[7]

其中p是polyfit输出的多项式数组。

有没有一种简单的方法可以反转这个方法,以便我可以得到以下形式的解决方案:

x(y) = p[0]*y^n + p[1]*y^n-1 + .... + p[n]*y^0

2
您是指使用py(x)值来获取新的x(y)p集合,还是使用相同的xy数据来找到新的p?如果是后者,在polyfit中只需交换xy即可... - Frank M
1个回答

2
  1. 一般来说,没有简单的方法。对于七次多项式,任意多项式的闭合形式解不可用

  2. 反向拟合是可能的,但仅限于原多项式单调变化的区域。如果原多项式在您感兴趣的域上具有极小值或最大值,则尽管y是x的函数,但x不能是y的函数,因为它们之间没有一对一的关系。

  3. 如果您(i)可以重新进行拟合过程,并且(ii)可以分段处理单个拟合的单调区域,则可以采取以下操作:

-

import numpy as np

# generate a random coefficient vector a
degree = 1
a = 2 * np.random.random(degree+1) - 1

# an assumed true polynomial y(x)
def y_of_x(x, coeff_vector):
    """
    Evaluate a polynomial with coeff_vector and degree len(coeff_vector)-1 using Horner's method.
    Coefficients are ordered by increasing degree, from the constant term at coeff_vector[0], 
        to the linear term at coeff_vector[1], to the n-th degree term at coeff_vector[n]
    """
    coeff_rev = coeff_vector[::-1]
    b = 0
    for a in coeff_rev:
        b = b * x + a
    return b


# generate some data
my_x = np.arange(-1, 1, 0.01)
my_y = y_of_x(my_x, a)


# verify that polyfit in the "traditional" direction gives the correct result
#     [::-1] b/c polyfit returns coeffs in backwards order rel. to y_of_x()
p_test = np.polyfit(my_x, my_y, deg=degree)[::-1]

print p_test, a

# fit the data using polyfit but with y as the independent var, x as the dependent var
p = np.polyfit(my_y, my_x, deg=degree)[::-1]

# define x as a function of y
def x_of_y(yy, a): 
    return y_of_x(yy, a)  


# compare results
import matplotlib.pyplot as plt
%matplotlib inline

plt.plot(my_x, my_y, '-b', x_of_y(my_y, p), my_y, '-r')

注意:此代码未检查单调性,仅假定其存在。

通过调整 degree 的值,您应该可以看到,只有在 degree=1 时,该代码适用于所有随机值的 a。 对于其他度数,它偶尔可以正常工作,但在存在许多极小值/极大值时不行。由于用平方根函数近似抛物线并不总是有效,因此对于degree>1,它永远不会完美地工作等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接