首页 > 解决方案 > 如何在 Python 中将条件设置为线性拟合?

问题描述

我有一组任意定义的点,我想将其拟合成线性关系 M = km+c,其中 k 是斜率,c 是某个常数。我还想设置 21(1-k)=c+5 的条件。

我已经使用 np.poly1d 和 sp.optimize.curve_fit 来查找 k 和 c 的值,这两个值都产生相同的值,但我找不到应用上述条件的方法。

这是 poly1d 版本:

arbitrary_x=[17.1,17.5,18.9,20.5]
arbitrary_y=[6,7,10,14]
plt.scatter (arbitrary_x, arbitrary_y, color='r', marker='x')

dparallax_fit = np.polyfit(arbitrary_x, arbitrary_y, 1)
j = np.poly1d(dparallax_fit)

x_dparallax_fit = np.linspace(16, 22, 100)
y_dparallax_fit = j(x_dparallax_fit)
plt.plot(x_dparallax_fit, y_dparallax_fit, color='purple')

这是 sp.optimize.curve_fit 选项。如您所见,我试图在 linear_fit 函数中断言条件,但无济于事:

m = np.linspace(16,22,100)

def find_lin_fit():
    #point and fit for the relationship between delta_parallax and d_max
    arbitrary_x=[17.1,17.5,18.9,20.5]
    arbitrary_y=[6,7,10,14]
    plt.scatter (arbitrary_x, arbitrary_y, color='r', marker='x')
    def linear_fit(m, k, c):
        #assert 21*(1-k)==c+5
        return k*m+c
    popt, pcov = sp.optimize.curve_fit(linear_fit, arbitrary_x, arbitrary_y)
    return popt, pcov

j = find_lin_fit()

plt.plot(m,j[0][0]*m+j[0][1], color='g')

两者的结果都是 ak=2.33, c=-33.88,但是,我再次希望满足 21(1-k)=c+5 的条件,即使拟合与实际的最佳拟合线略有不同。

此外,请随时指出我的代码中与约定或冗余的任何偏差。

编辑:为了更具体地说明我所说的“发散”,我希望拟合线来定义图像中点的限制。您将能够在上面标有红色 x 的图像中看到任意点。使用其中一个值来找到另一个值并不能准确地满足限制,我仍然需要满足条件才能在以后的工作步骤中准确。本质上,我需要这条线在两个参数上略有不同,同时保持数据限制的准确表示。

标签: pythonnumpyscipycurve-fitting

解决方案


推荐阅读