python numpy/scipy 曲线拟合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19165259/
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
python numpy/scipy curve fitting
提问by Bob
I have some points and I am trying to fit curve for this points. I know that there exist scipy.optimize.curve_fit
function, but I do not understand documentation, i.e how to use this function.
我有一些要点,我正在尝试为这些点拟合曲线。我知道存在scipy.optimize.curve_fit
函数,但我不了解文档,即如何使用此函数。
My points: np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
我的观点: np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
Can anybody explain how to do that?
任何人都可以解释如何做到这一点?
采纳答案by jabaldonedo
I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit
tries to fit a function f
that you must know to a set of points.
我建议您从简单的多项式拟合开始,scipy.optimize.curve_fit
尝试将f
您必须知道的函数拟合到一组点。
This is a simple 3 degree polynomial fit using numpy.polyfit
and poly1d
, the first performs a least squares polynomial fit and the second calculates the new points:
这是一个简单的 3 度多项式拟合,使用numpy.polyfit
和poly1d
,第一个执行最小二乘多项式拟合,第二个计算新点:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
#?get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
#?calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
回答by Greg
You'll first need to separate your numpy array into two separate arrays containing x and y values.
您首先需要将 numpy 数组分成两个单独的包含 x 和 y 值的数组。
x = [1, 2, 3, 9]
y = [1, 4, 1, 3]
curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like
curve_fit 还需要一个函数来提供您想要的拟合类型。例如,线性拟合将使用类似的函数
def func(x, a, b):
return a*x + b
scipy.optimize.curve_fit(func, x, y)
will return a numpy array containing two arrays: the first will contain values for a
and b
that best fit your data, and the second will be the covariance of the optimal fit parameters.
scipy.optimize.curve_fit(func, x, y)
将返回包含两个阵列一个numpy的阵列:首先将包含值a
和b
最适合你的数据,和第二个将是最佳拟合参数的协方差。
Here's an example for a linear fit with the data you provided.
这是与您提供的数据进行线性拟合的示例。
import numpy as np
from scipy.optimize import curve_fit
x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])
def fit_func(x, a, b):
return a*x + b
params = curve_fit(fit_func, x, y)
[a, b] = params[0]
This code will return a = 0.135483870968
and b = 1.74193548387
此代码将返回a = 0.135483870968
并b = 1.74193548387
Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.
这是一个带有您的点和线性拟合的图......这显然是一个不好的图,但是您可以更改拟合函数以获得您想要的任何类型的拟合。