# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import sympy as sym
"""
Generate some data, let's imagine that you already have this.
"""
x = np.linspace(0, 3, 50)
y = np.exp(x)
"""
Plot your data
"""
plt.plot(x, y, 'ro',label="Original Data")
"""
brutal force to avoid errors
"""
x = np.array(x, dtype=float) #transform your data in a numpy array of floats
y = np.array(y, dtype=float) #so the curve_fit can work
"""
create a function to fit with your data. a, b, c and d are the coefficients
that curve_fit will calculate for you.
In this part you need to guess and/or use mathematical knowledge to find
a function that resembles your data
"""
def func(x, a, b, c, d):
return a*x**3 + b*x**2 +c*x + d
"""
make the curve_fit
"""
popt, pcov = curve_fit(func, x, y)
"""
The result is:
popt[0] = a , popt[1] = b, popt[2] = c and popt[3] = d of the function,
so f(x) = popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3].
"""
print "a = %s , b = %s, c = %s, d = %s" % (popt[0], popt[1], popt[2], popt[3])
"""
Use sympy to generate the latex sintax of the function
"""
xs = sym.Symbol('\lambda')
tex = sym.latex(func(xs,*popt)).replace('$', '')
plt.title(r'$f(\lambda)= %s$' %(tex),fontsize=16)
"""
Print the coefficients and plot the funcion.
"""
plt.plot(x, func(x, *popt), label="Fitted Curve") #same as line above \/
#plt.plot(x, popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3], label="Fitted Curve")
plt.legend(loc='upper left')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x, yn)
为了拟合y=A+Blogx,只需拟合y对(logx)。
为了拟合y=AeBx,取两边的对数,得出logy=logA+Bx。因此,将(logy)与x进行拟合。
注意,拟合(logy)如果是线性的,将强调y的小值,从而导致大y的大偏差。这是因为
polyfit
(线性回归)的工作原理是最小化∑i(ΔY)2=∑i(Yi-i)2。>i|。因此,即使polyfit
对大的y做出了一个非常糟糕的决定,“除以-|y}”因子也会对其进行补偿,从而导致polyfit
倾向于较小的值。这可以通过给每个条目一个与y成比例的“权重”来缓解。
polyfit
通过w
关键字参数支持加权最小二乘法。请注意,Excel、LibreOffice和大多数科学计算器通常使用指数回归/趋势线的未加权(有偏)公式。如果希望结果与这些平台兼容,即使提供更好的结果,也不要包含权重。
现在,如果可以使用scipy,则可以使用^{} 来适应任何模型,而无需转换。
对于y=A+Blogx结果与转换方法相同:
对于y=AeBx,由于它直接计算Δ(logy),我们可以得到更好的拟合。但我们需要提供一个初始化猜测,以便
curve_fit
可以达到所需的本地最小值。我有一些麻烦,所以让我非常明确,这样像我这样的人可以理解。
假设我们有一个数据文件之类的
结果是: a=0.849195983017,b=-1.18101681765,c=2.24061176543,d=0.816643894816
您还可以使用
scipy.optimize
中的curve_fit
将一组数据适合您喜欢的任何函数。例如,如果要拟合指数函数(来自documentation):如果你想绘图,你可以:
(注意:绘图时
*
前面的popt
将扩展到a
、b
和c
中,这是func
所期望的。)相关问题 更多 >
编程相关推荐