代码之家  ›  专栏  ›  技术社区  ›  SuperCiocia

python:用共享参数拟合矩阵方程

  •  1
  • SuperCiocia  · 技术社区  · 6 年前

    我有两个方程来源于一个矩阵方程:

    [x,y] = [[cos(n), -sin(n)],[sin(n), cos(n)]]*[x', y'] ,

    哪里 x' = Acos(w1*t+ p1) y' = Bcos(w2*t + p2) .

    这只是向量的一个矩阵方程 [x,y] ,但它可以分解为两个标量方程: x = A*cos(s)*cos(w1*t+ p1)*x' - B*sin(s)*sin(w2*t + p2)*y' y = A*sin(s)*cos(w1*t+ p1)*x' + B*cos(s)*sin(w2*t + p2)*y' .

    所以我拟合了两个数据集, x VS t y VS T ,但在这些拟合中有一些共享参数,即 A , B s .

    1)我可以直接拟合矩阵方程,还是必须将其分解成标量方程?前者会更优雅。

    2)我能适应共享参数吗? curve_fit ?所有相关问题使用其他软件包。

    1 回复  |  直到 6 年前
        1
  •  1
  •   James Phillips    6 年前

    下面的示例代码使用CurvyFIT拟合一个共享参数的两个不同的方程。这不是对您问题的回答,但我无法在注释中设置代码格式,因此我将在此处发布。

    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    
    y1 = np.array([ 16.00,  18.42,  20.84,  23.26,  25.68])
    y2 = np.array([-20.00, -25.50, -31.00, -36.50, -42.00])
    comboY = np.append(y1, y2)
    
    h = np.array([5.0, 6.1, 7.2, 8.3, 9.4])
    comboX = np.append(h, h)
    
    
    def mod1(data, a, b, c): # not all parameters are used here
            return a * data + c
    
    
    def mod2(data, a, b, c): # not all parameters are used here
            return b * data + c
    
    
    def comboFunc(comboData, a, b, c):
        # single data set passed in, extract separate data
        extract1 = comboData[:len(y1)] # first data
        extract2 = comboData[len(y2):] # second data
    
        result1 = mod1(extract1, a, b, c)
        result2 = mod2(extract2, a, b, c)
    
        return np.append(result1, result2)
    
    
    # some initial parameter values
    initialParameters = np.array([1.0, 1.0, 1.0])
    
    # curve fit the combined data to the combined function
    fittedParameters, pcov = curve_fit(comboFunc, comboX, comboY, initialParameters)
    
    # values for display of fitted function
    a, b, c = fittedParameters
    
    y_fit_1 = mod1(h, a, b, c) # first data set, first equation
    y_fit_2 = mod2(h, a, b, c) # second data set, second equation
    
    plt.plot(comboX, comboY, 'D') # plot the raw data
    plt.plot(h, y_fit_1) # plot the equation using the fitted parameters
    plt.plot(h, y_fit_2) # plot the equation using the fitted parameters
    plt.show()
    
    print(fittedParameters)