【问题标题】:Python Library for Multivariate Spline Interpolation用于多元样条插值的 Python 库
【发布时间】:2023-03-08 17:44:01
【问题描述】:

是否有用于多元插值的 python 库?现在我有三个自变量和一个因变量。我的数据如下所示:

X1=[3,3,3.1,3.1,4.2,5.2,6.3,2.3,7.4,8.4,5.4,3.4,3.4,3.4,...]
X2=[12.1,12.7,18.5,18.3,18.4,18.6,24.2,24.4,24.3,24.5,30.9,30.7,30.3,30.4,6.1,6.2,...]
X3=[0.3,9.2,0.3,9.4,0.1,9.8,0.4,9.3,0.7,9.7,18.3,27.4,0.6,9.44,...]
Y=[-5.890,-5.894,2.888,-3.8706,2.1516,-2.7334,1.4723,-2.1049,0.9167,-1.7281,-2.091,-6.7394,0.8777,-1.7046,...]
and len(X1)=len(X2)=len(X3)=len(Y)=400

我想拟合或插值数据,以便给定任意 x1, x2, x3 值,函数 f(x1,x2,x3) 将产生估计的 y 值。就像给定x1=4.11, x2=10.34, and x3=10.78, 一样,该函数将产生-8.7567(best estimate). 我想该函数将是多项式的。所以也许样条插值是最好的选择?

【问题讨论】:

    标签: python scipy interpolation spline


    【解决方案1】:

    curve_fit 在 scipy.optimize 中工作。在这段代码中,估计是线性函数,但它可能更好。

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    
    X1=[3,3,3.1,3.1,4.2,5.2,6.3,2.3,7.4,8.4,5.4,3.4,3.4,3.4]
    X2=[12.1,12.7,18.5,18.3,18.4,18.6,24.2,24.4,24.3,24.5,30.9,30.7,30.3,30.4]
    X3=[0.3,9.2,0.3,9.4,0.1,9.8,0.4,9.3,0.7,9.7,18.3,27.4,0.6,9.44]
    Y=[-5.890,-5.894,2.888,-3.8706,2.1516,-2.7334,1.4723,-2.1049,0.9167,-1.7281,-2.091,-6.7394,0.8777,-1.7046]
    
    def fitFunc(x, a, b, c, d):
        return a + b*x[0] + c*x[1] + d*x[2]
    
    fitParams, fitCovariances = curve_fit(fitFunc, [X1, X2, X3], Y)
    print(' fit coefficients:\n', fitParams)
    # fit coefficients:
    #  [-6.11934208  0.21643939  0.26186705 -0.33794415]
    

    然后用fitParams[0] + fitParams[1] * x1 + fitParams[2] * x2 + fitParams[3] * x3估计y。

    # get single y
    def estimate(x1, x2, x3):
        return fitParams[0] + fitParams[1] * x1 + fitParams[2] * x2 + fitParams[3] * x3
    

    将结果与原始 y 进行比较。

    Y_estimated = [estimate(X1[i], X2[i], X3[i]) for i in range(len(X1))]
    
    fig, ax = plt.subplots()
    ax.scatter(Y, Y_estimated)
    
    lims = [
        np.min([ax.get_xlim(), ax.get_ylim()]),  # min of both axes
        np.max([ax.get_xlim(), ax.get_ylim()]),  # max of both axes
    ]
    
    ax.set_xlabel('Y')
    ax.set_ylabel('Y_estimated')
    ax.plot(lims, lims, 'k-', alpha=0.75, zorder=0)
    ax.set_aspect('equal')
    

    参考scipystackoverflow-multifitstackoverflow-plot xy

    【讨论】:

      猜你喜欢
      • 2011-09-08
      • 2018-02-12
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 2021-12-06
      • 2023-01-03
      相关资源
      最近更新 更多