python - 如何在 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 的图像中看到任意点。使用其中一个值来找到另一个值并不能准确地满足限制,我仍然需要满足条件才能在以后的工作步骤中准确。本质上,我需要这条线在两个参数上略有不同,同时保持数据限制的准确表示。
解决方案
推荐阅读
- java - kafka 生产者在消息之间能存活多久?
- buffer - 让 Neovim 使用 tmux 缓冲区和系统剪贴板作为两个寄存器
- javascript - 使用 htmx 动态地将表单添加到 Django 表单集?
- r - 同时使用 geom_tex 时来自 ggplot 的错误代码
- python - 为什么 Sqlite 会创建一个我没有在我的 create_tables.py 文件中指定的新表
- flutter - 模拟器在android studio中不起作用
- github-actions - 通过非交互式会话通过 SSH 连接到服务器时找不到命令
- php - Symfony4:在属性路径“categorie”处给出“Categorie”类型的预期参数,“App\Entity\Categorie 的实例”
- reactjs - React Hook Form V7 - Material UI 5 Autocomplete:延迟加载的值未验证
- javascript - 使用 javascript/jquery 在按下键上/下时选择选项