gpt4 book ai didi

python - 点下方的线拟合

转载 作者:太空狗 更新时间:2023-10-30 03:04:45 25 4
gpt4 key购买 nike

我有一组 x、y 点,我想使用 SciPy 找到最适合的线,使该线低于所有点。我正在尝试为此使用 leastsq,但我不确定如何将线调整为低于所有点而不是最佳拟合线。最佳拟合线的系数可以通过以下方式产生:

def linreg(x, y):

fit = lambda params, x: params[0] * x - params[1]
err = lambda p, x, y: (y - fit(p, x))**2

# initial slope/intercept
init_p = np.array((1, 0))

p, _ = leastsq(err, init_p.copy(), args=(x, y))

return p

xs = sp.array([1, 2, 3, 4, 5])
ys = sp.array([10, 20, 30, 40, 50])

print linreg(xs, ys)

输出是最佳拟合线的系数:

array([  9.99999997e+00,  -1.68071668e-15])

如何获取所有点下方的最佳拟合线的系数?

最佳答案

一种可能的算法如下:

  1. 移动轴以使所有数据位于 x 轴的正半部分。

  2. 如果拟合的形式为 y = a * x + b , 然后对于给定的 b最适合 a将是连接点 (0, b) 的最小斜率每个 (x, y)积分。

  3. 然后您可以计算拟合误差,它仅是 b 的函数,并使用 scipy.optimize.minimize找到 b 的最佳值.

  4. 剩下的就是计算 a为此b并计算b为轴的原始位置。

下面的大部分时间都是这样做的,除非最小化因某些神秘错误而失败:

from __future__ import division
import numpy as np
import scipy.optimize
import matplotlib.pyplot as plt

def fit_below(x, y) :
idx = np.argsort(x)
x = x[idx]
y = y[idx]
x0, y0 = x[0] - 1, y[0]
x -= x0
y -= y0

def error_function_2(b, x, y) :
a = np.min((y - b) / x)
return np.sum((y - a * x - b)**2)

b = scipy.optimize.minimize(error_function_2, [0], args=(x, y)).x[0]

a = np.min((y - b) / x)

return a, b - a * x0 + y0

x = np.arange(10).astype(float)
y = x * 2 + 3 + 3 * np.random.rand(len(x))

a, b = fit_below(x, y)

plt.plot(x, y, 'o')
plt.plot(x, a*x + b, '-')
plt.show()

正如 TheodrosZelleke 明智地预测的那样,它经过凸包的两个点:

enter image description here

关于python - 点下方的线拟合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com