[英]python numpy/scipy curve fitting
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, ie 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?任何人都可以解释如何做到这一点?
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:这是使用
numpy.polyfit
和poly1d
的简单 3 度多项式拟合,第一个执行最小二乘多项式拟合,第二个计算新点:
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()
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. curve_fit 还需要一个函数来提供您想要的拟合类型。 For instance, a linear fit would use a function like
例如,线性拟合将使用类似的函数
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.这是一个带有您的点和线性拟合的图......这显然是一个不好的图,但是您可以更改拟合函数以获得您想要的任何类型的拟合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.