简体   繁体   English

Python 中的最佳拟合线不准确

[英]Line of best fit not accurate in Python

I am trying to create a line of best fit for a small scatter plot.我正在尝试为小散点 plot 创建一条最适合的线。 Right now I am using现在我正在使用

m,b = np.polyfit(xArray, yArray, 1)
xValues = np.linspace(-8,2,50)

plt.scatter(xList, yList)
plt.plot(xValues, m*xValues+b)

This keeps giving me a reasonable line of best fit, but what I am looking for is a more vertical line.这一直给我一个合理的最佳拟合线,但我正在寻找的是一条更垂直的线。 What could I use as a substitue to polyfit when the data has a much higher down trend like this one?当数据具有像这样更高的下降趋势时,我可以用什么来代替 polyfit?

Calculated best fit line:计算出的最佳拟合线:

计算出的最佳拟合线

Using orthogonal least squares instead of polyfit gives the desired answer.使用正交最小二乘法而不是 polyfit 可以得到所需的答案。 There is a built in package for this within scipy.在 scipy 中有一个内置的 package 用于此。

from scipy import odr

def linear_func(p, x):
   m, c = p
   return m*x + c

#Create a Model.:
linear = odr.Model(linear_func)

#Create a Data or RealData instance.:
mydata = odr.Data(xArray, yArray)

#or, when the actual covariances are known:
mydata = odr.RealData(x, y, sx=sx, sy=sy)

#Instantiate ODR with your data, model and initial parameter estimate.:
myodr = odr.ODR(mydata, linear, beta0=[1., 2.])

#Run the fit.:
myoutput = myodr.run()

#Examine output.:
myoutput.pprint()

例子

Instead of vertical distance to each point, this method uses perpendicular distance as shown above.此方法不是到每个点的垂直距离,而是使用如上所示的垂直距离。 This gives better fits for when your data has a strong down or up trend.当您的数据具有强烈的下降或上升趋势时,这将更适合。

There are more detailed explanations on how to use this method here.这里有关于如何使用这个方法的更详细的解释。

referece: documentation参考:文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM