最小二乘拟合直线 python 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22240280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:33:19  来源:igfitidea点击:

Least-Squares Fit to a Straight Line python code

pythonplot

提问by Astronerd326

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 和 Y 坐标组成的散点图。我想对直线使用最小二乘拟合来获得最佳拟合线。

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.

Least-Squares Fit to a Straight 是指:如果(x_1,y_1),.....(x_n,y_n) 是测量数据对,那么最好的直线是y = A + Bx。

Here is my code in python:

这是我在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)

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

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

采纳答案by ycy

If I understand your question correctly, you have two datasets xand ywhere you want to perform a least square fit.

如果我正确理解您的问题,那么您有两个数据集x以及y您想要执行最小二乘拟合的位置。

You don't have to write the algorithm yourself, curve_fitfrom scipy.optimizeshould do what you want, try:

你不必自己编写算法,curve_fitscipy.optimize应该做你想做的,尝试:

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

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

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

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

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

回答by ysakamoto

You are trying to multiply two lists xand y(or by itself) but it is not defined in Python. You either need to write your own function to do the list element-by-element multiplication or use numpy.multiply. For example, if you want to do elemet-wise multiplication of x and y,

您正在尝试将两个列表xy(或单独)相乘,但它没有在 Python 中定义。您要么需要编写自己的函数来执行列表逐元素乘法,要么使用numpy.multiply. 例如,如果你想对 x 和 y 进行元素乘法,

import numpy as np
xy = np.multiply(x,y)

回答by fantabolous

Simplest if you just want a line is scipy.stats.linregress:

如果您只想要一行,最简单的是scipy.stats.linregress

>>> from scipy import stats
>>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

Link to docs

链接到文档