【问题标题】:Simultaneously fit two linear functions with a single slope [closed]同时拟合具有单个斜率的两个线性函数[关闭]
【发布时间】:2019-05-30 13:19:02
【问题描述】:

我有两组实验数据,如图 对于,两组的测量数据必须相同。因此,我想同时拟合两组,定义一个 y 截距和两个斜率。据我了解,this question 并没有解决我的问题。

【问题讨论】:

    标签: python statistics


    【解决方案1】:

    我想你会做一个simple linear regression。这里的问题是最小化具有相同截距的两个线性函数的误差。误差函数为:

    def f(params):
        alpha, betha_1, betha_2 = params
        e_1 = np.power(y1- alpha - (betha_1 * x),2)
        e_2 = np.power(y2- alpha - (betha_2 * x),2)
        error = np.sum(e_1 + e_2)
        return error
    

    我使用scipy.optimize.minimize 来获得最佳参数。最终代码为:

    import numpy as np
    from scipy.optimize import minimize
    import matplotlib.pyplot as plt
    
    y2 = [9, 11, 10, 12, 13, 12, 12]
    y1 = [10, 12, 11, 12, 12, 13, 14]
    x = [0, 1, 2, 3, 4, 5, 6]
    x, y1, y2 = np.array(x), np.array(y1), np.array(y2)
    
    def f(params):
        alpha, betha_1, betha_2 = params
        e_1 = np.power(y1- alpha - (betha_1 * x),2)
        e_2 = np.power(y2- alpha - (betha_2 * x),2)
        error = np.sum(e_1 + e_2)
        return error
    
    initial_guess = [1, 1, 1]
    result = minimize(f, initial_guess)
    
    xfine = np.arange(0, 6, 0.001)
    y1_reg = result.x[0] + result.x[1]*xfine
    y2_reg = result.x[0] + result.x[2]*xfine
    
    plt.plot(x, y1, 'bo', x, y2, 'go', xfine, y1_reg, 'b', xfine, y2_reg, 'g')
    plt.show()
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多