在python上实现永无止境的矩阵公式以进行曲线拟合

问题描述 投票:1回答:1

我正在尝试编写一个可以解决一般回归公式的程序:So I'm trying to implement this matrix equation,是否总有这样的方法可以让用户决定它的大小,而无需我做越来越多的条件(因此只有一段代码会折叠到用户希望的矩阵中)?代码:

    #Solving the general matrix for the coefficients
if 3 == n:
    a = np.array([[np.sum(np.multiply(FL[1],FL[1])),np.sum(np.multiply(FL[1],FL[2]))],
                    [np.sum(np.multiply(FL[1],FL[2])),np.sum(np.multiply(FL[2],FL[2]))]])
    b = np.array([np.sum(np.multiply(FL[0],FL[1])),np.sum(np.multiply(FL[0],FL[2]))])
    x = np.linalg.solve(a, b)
if 4 == n:
    a = np.array([[np.sum(np.multiply(FL[1],FL[1])),np.sum(np.multiply(FL[1],FL[2])),np.sum(np.multiply(FL[1],FL[3]))],
                    [np.sum(np.multiply(FL[1],FL[2])),np.sum(np.multiply(FL[2],FL[2])),np.sum(np.multiply(FL[2],FL[3]))],
                    [np.sum(np.multiply(FL[1],FL[3])),np.sum(np.multiply(FL[2],FL[3])),np.sum(np.multiply(FL[3],FL[3]))]])
    b = np.array([np.sum(np.multiply(FL[0],FL[1])),np.sum(np.multiply(FL[0],FL[2])),np.sum(np.multiply(FL[0],FL[3]))])
    x = np.linalg.solve(a, b)

[1在此代码中,Phi_0对应于FL [i = 1],FL [0]对应于y。

python recursion iteration curve-fitting
1个回答
1
投票

您可以使算法独立于多项式的阶数。最简单的方法是使用for循环,尽管它们会很慢(因为它们不利用NumPy的向量化)。这是带有随机数据的可重现示例:

© www.soinside.com 2019 - 2024. All rights reserved.