最小二乘拟合直线 python 代码 [英] Least-Squares Fit to a Straight Line python code

查看:56
本文介绍了最小二乘拟合直线 python 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由 X 和 Y 坐标组成的散点图.我想对直线使用最小二乘拟合来获得最佳拟合线.

I have a scatter plot composed of X and Y coordinates. I want to use the Least-Squares Fit to a Straight Line to obtain the line of best fit.

拟合直线的最小二乘法是指:如果(x_1,y_1),.....(x_n,y_n)是测得的数据对,那么最好的直线是y = A + Bx.

The Least-Squares Fit to a Straight Line refers to: If(x_1,y_1),....(x_n,y_n) are measured pairs of data, then the best straight line is y = A + Bx.

这是我的python代码:

Here is my code in python:

 # number of points is 50
 A = (sum(x**2)*sum(y) - sum(x)*sum(x*y)) / (50*sum(x**2) - (sum(x))**2)
 B = (50*sum(x*y) - sum(x)*sum(y)) / (50*sum(x**2) - (sum(x))**2)
 print (A,B)

这看起来正确吗,我在打印 A 和 B 时遇到问题.谢谢!

Does this look correct, I'm having issues printing A and B. Thank you!

推荐答案

如果我正确理解你的问题,你有两个数据集 xy 要在其中执行最小二乘拟合.

If I understand your question correctly, you have two datasets x and y where you want to perform a least square fit.

您不必自己编写算法,scipy.optimize 中的 curve_fit 应该可以做您想做的事,请尝试:

You don't have to write the algorithm yourself, curve_fit from scipy.optimize should do what you want, try:

from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

popt, pcov = curve_fit(f, x, y) # your data x, y to fit

其中 popt[0], popt[1] 是直线的斜率和截距.

where popt[0], popt[1] would be the slope and intercept of the straight line.

有关更多详细信息和示例,请参阅:http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html#scipy.optimize.curve_fit

For more details and examples, see: http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html#scipy.optimize.curve_fit

这篇关于最小二乘拟合直线 python 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆