相当于Python中2D多项式的"polyfit"

Jus*_*sch 13 python math numpy linear-algebra polynomial-math

我想找到a系数的最小二乘解

z = (a0 + a1*x + a2*y + a3*x**2 + a4*x**2*y + a5*x**2*y**2 + a6*y**2 +
     a7*x*y**2 + a8*x*y)
Run Code Online (Sandbox Code Playgroud)

给定的阵列x,yz长度20的基本上我正在寻找的等效numpy.polyfit但对于一个二维多项式.

这个问题很相似,但解决方案是通过MATLAB提供的.

Sau*_*tro 15

以下是一个示例,说明如何使用numpy.linalg.lstsq此任务:

import numpy as np

x = np.linspace(0, 1, 20)
y = np.linspace(0, 1, 20)
X, Y = np.meshgrid(x, y, copy=False)
Z = X**2 + Y**2 + np.random.rand(*X.shape)*0.01

X = X.flatten()
Y = Y.flatten()

A = np.array([X*0+1, X, Y, X**2, X**2*Y, X**2*Y**2, Y**2, X*Y**2, X*Y]).T
B = Z.flatten()

coeff, r, rank, s = np.linalg.lstsq(A, B)
Run Code Online (Sandbox Code Playgroud)

调整系数coeff是:

array([ 0.00423365,  0.00224748,  0.00193344,  0.9982576 , -0.00594063,
        0.00834339,  0.99803901, -0.00536561,  0.00286598])
Run Code Online (Sandbox Code Playgroud)

请注意,coeff[3]并且coeff[6]分别对应于X**2Y**2,并且它们接近,1.因为示例数据是使用创建的Z = X**2 + Y**2 + small_random_component.


Pad*_*son 8

根据@Saullo 和@Francisco 的回答,我创建了一个我发现有用的函数:

def polyfit2d(x, y, z, kx=3, ky=3, order=None):
    '''
    Two dimensional polynomial fitting by least squares.
    Fits the functional form f(x,y) = z.

    Notes
    -----
    Resultant fit can be plotted with:
    np.polynomial.polynomial.polygrid2d(x, y, soln.reshape((kx+1, ky+1)))

    Parameters
    ----------
    x, y: array-like, 1d
        x and y coordinates.
    z: np.ndarray, 2d
        Surface to fit.
    kx, ky: int, default is 3
        Polynomial order in x and y, respectively.
    order: int or None, default is None
        If None, all coefficients up to maxiumum kx, ky, ie. up to and including x^kx*y^ky, are considered.
        If int, coefficients up to a maximum of kx+ky <= order are considered.

    Returns
    -------
    Return paramters from np.linalg.lstsq.

    soln: np.ndarray
        Array of polynomial coefficients.
    residuals: np.ndarray
    rank: int
    s: np.ndarray

    '''

    # grid coords
    x, y = np.meshgrid(x, y)
    # coefficient array, up to x^kx, y^ky
    coeffs = np.ones((kx+1, ky+1))

    # solve array
    a = np.zeros((coeffs.size, x.size))

    # for each coefficient produce array x^i, y^j
    for index, (j, i) in enumerate(np.ndindex(coeffs.shape)):
        # do not include powers greater than order
        if order is not None and i + j > order:
            arr = np.zeros_like(x)
        else:
            arr = coeffs[i, j] * x**i * y**j
        a[index] = arr.ravel()

    # do leastsq fitting and return leastsq result
    return np.linalg.lstsq(a.T, np.ravel(z), rcond=None)
Run Code Online (Sandbox Code Playgroud)

结果拟合可以通过以下方式可视化:

fitted_surf = np.polynomial.polynomial.polyval2d(x, y, soln.reshape((kx+1,ky+1)))
plt.matshow(fitted_surf)
Run Code Online (Sandbox Code Playgroud)

  • 此答案的建议编辑队列已满,听起来人们已尝试提交超过 500 个编辑。对于遇到此问题的其他人,底部的“polyval2d”应该是“polygrid2d”,如评论中所述。`soln` 是返回值的第一部分,再次如注释中所述。我还建议放置完整的代码来调用您的代码/图,但这对于评论来说太多了。我非常感谢您的回答,我只是认为如果有更强大的使用示例,人们可能会更容易使用。 (2认同)

小智 6

索洛·卡斯特罗的出色回答。只需添加代码以使用 a 系数的最小二乘解来重建函数,

def poly2Dreco(X, Y, c):
    return (c[0] + X*c[1] + Y*c[2] + X**2*c[3] + X**2*Y*c[4] + X**2*Y**2*c[5] + 
           Y**2*c[6] + X*Y**2*c[7] + X*Y*c[8])
Run Code Online (Sandbox Code Playgroud)