如何在Python中进行指数和对数曲线拟合?我发现只有多项式拟合
我有一组数据,我想比较哪一行最能描述它(不同阶数的多项式,指数或对数) 我使用Python和Numpy,对于多项式拟合,有一个函数如何在Python中进行指数和对数曲线拟合?我发现只有多项式拟合,python,numpy,scipy,curve-fitting,linear-regression,Python,Numpy,Scipy,Curve Fitting,Linear Regression,我有一组数据,我想比较哪一行最能描述它(不同阶数的多项式,指数或对数) 我使用Python和Numpy,对于多项式拟合,有一个函数polyfit()。但我没有发现这样的指数和对数拟合函数 有吗?或者如何解决它?对于拟合y=A+B对数x,只需将y与(对数x)拟合即可 对于拟合y=AeBx,取两边的对数,得到log y=log A+Bx。因此,将(对数y)与x进行拟合 请注意,线性拟合(对数y)将强调y的小值,从而导致大y的大偏差。这是因为polyfit(线性回归)通过最小化∑i(ΔY)2=∑一(
polyfit()
。但我没有发现这样的指数和对数拟合函数
有吗?或者如何解决它?对于拟合y=A+B对数x,只需将y与(对数x)拟合即可
对于拟合y=AeBx,取两边的对数,得到log y=log A+Bx。因此,将(对数y)与x进行拟合 请注意,线性拟合(对数y)将强调y的小值,从而导致大y的大偏差。这是因为
polyfit
(线性回归)通过最小化∑i(ΔY)2=∑一(易)− Ŷi)2。当Yi=log Yi时,残留物ΔYi=Δ(log Yi)≈ Δyi/| yi |。因此,即使polyfit
对大y做出了非常糟糕的决定,“除以-| y |”因子也会对其进行补偿,从而导致polyfit
偏向小值
这可以通过给每个条目一个与y成比例的“权重”来缓解polyfit
通过w
关键字参数支持加权最小二乘法
>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> numpy.polyfit(x, numpy.log(y), 1)
array([ 0.10502711, -0.40116352])
# y ≈ exp(-0.401) * exp(0.105 * x) = 0.670 * exp(0.105 * x)
# (^ biased towards small values)
>>> numpy.polyfit(x, numpy.log(y), 1, w=numpy.sqrt(y))
array([ 0.06009446, 1.41648096])
# y ≈ exp(1.42) * exp(0.0601 * x) = 4.12 * exp(0.0601 * x)
# (^ not so biased)
请注意,Excel、LibreOffice和大多数科学计算器通常对指数回归/趋势线使用未加权(有偏)公式。如果您希望结果与这些平台兼容,请不要包含权重,即使它提供了更好的结果
现在,如果您可以使用scipy,那么您可以使用它来拟合任何模型,而无需进行转换 对于y=A+B log x,结果与转换方法相同:
>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> scipy.optimize.curve_fit(lambda t,a,b: a+b*numpy.log(t), x, y)
(array([ 6.61867467, 8.46295606]),
array([[ 28.15948002, -7.89609542],
[ -7.89609542, 2.9857172 ]]))
# y ≈ 6.62 + 8.46 log(x)
然而,对于y=AeBx,我们可以得到更好的拟合,因为它直接计算Δ(logy)。但我们需要提供一个初始化猜测,以便曲线拟合
能够达到所需的局部最小值
>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t), x, y)
(array([ 5.60728326e-21, 9.99993501e-01]),
array([[ 4.14809412e-27, -1.45078961e-08],
[ -1.45078961e-08, 5.07411462e+10]]))
# oops, definitely wrong.
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t), x, y, p0=(4, 0.1))
(array([ 4.88003249, 0.05531256]),
array([[ 1.01261314e+01, -4.31940132e-02],
[ -4.31940132e-02, 1.91188656e-04]]))
# y ≈ 4.88 exp(0.0553 x). much better.
您还可以使用
scipy.optimize中的curve\u fit
将一组数据拟合到您喜欢的任何函数。例如,如果要拟合指数函数(从中):
如果你想绘图,你可以:
plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()
(注意:绘图时,popt
前面的*
会将术语展开为a
、b
和c
,这是func
所期望的。)我在这方面遇到了一些问题,所以让我非常明确,这样像我这样的人都能理解
假设我们有一个数据文件或类似的东西
# -*- 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()
结果是:
a=0.849195983017,b=1.18101681765,c=2.24061176543,d=0.816643894816
我想您可以随时使用:
np.log --> natural log
np.log10 --> base 10
np.log2 --> base 2
稍微修改:
这将导致以下图表:
这里有一个简单数据选项,它使用来自的工具
给定的
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import FunctionTransformer
np.random.seed(123)
import lmfit
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(123)
代码
拟合指数数据
# Data
x_samp, y_samp = generate_data(func_exp, 2.5, 1.2, 0.7, jitter=3)
y_trans = transformer.fit_transform(y_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_samp, y_trans) # 2
model = results.predict
y_fit = model(x_samp)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, np.exp(y_fit), "k--", label="Fit") # 3
plt.title("Exponential Fit")
regressor = lmfit.models.ExponentialModel() # 1
initial_guess = dict(amplitude=1, decay=-1) # 2
results = regressor.fit(y_samp, x=x_samp, **initial_guess)
y_fit = results.best_fit
plt.plot(x_samp, y_samp, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()
拟合日志数据
# Data
x_samp, y_samp = generate_data(func_log, 2.5, 1.2, 0.7, jitter=0.15)
x_trans = transformer.fit_transform(x_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_trans, y_samp) # 2
model = results.predict
y_fit = model(x_trans)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, y_fit, "k--", label="Fit") # 3
plt.title("Logarithmic Fit")
regressor = lmfit.Model(func_log) # 1
initial_guess = dict(a=1, b=.1, c=.1) # 2
results = regressor.fit(y_samp2, x=x_samp, **initial_guess)
y_fit = results.best_fit
plt.plot(x_samp, y_samp2, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()
详细信息
一般步骤
将日志操作应用于数据值(x
、y
或两者)
将数据回归到线性化模型
通过“反转”任何日志操作(使用np.exp()
)进行绘图,并与原始数据相匹配
假设我们的数据遵循指数趋势,一般方程+可能是:
我们可以通过以下公式将后一个方程线性化(例如y=截距+斜率*x):
给定线性化方程++和回归参数,我们可以计算:
A
通过截获(ln(A)
)
B
通过坡度(B
)
线性化技术综述
+注:当噪声较小且C=0时,线性化指数函数效果最佳。小心使用
++注:改变x数据有助于指数数据线性化,改变y数据有助于对数数据线性化。我们在解决这两个问题时演示了的功能
给定的
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import FunctionTransformer
np.random.seed(123)
import lmfit
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(123)
代码
方法1-lmfit
模型
拟合指数数据
# Data
x_samp, y_samp = generate_data(func_exp, 2.5, 1.2, 0.7, jitter=3)
y_trans = transformer.fit_transform(y_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_samp, y_trans) # 2
model = results.predict
y_fit = model(x_samp)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, np.exp(y_fit), "k--", label="Fit") # 3
plt.title("Exponential Fit")
regressor = lmfit.models.ExponentialModel() # 1
initial_guess = dict(amplitude=1, decay=-1) # 2
results = regressor.fit(y_samp, x=x_samp, **initial_guess)
y_fit = results.best_fit
plt.plot(x_samp, y_samp, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()
方法2-自定义模型
拟合日志数据
# Data
x_samp, y_samp = generate_data(func_log, 2.5, 1.2, 0.7, jitter=0.15)
x_trans = transformer.fit_transform(x_samp) # 1
# Regression
regressor = LinearRegression()
results = regressor.fit(x_trans, y_samp) # 2
model = results.predict
y_fit = model(x_trans)
# Visualization
plt.scatter(x_samp, y_samp)
plt.plot(x_samp, y_fit, "k--", label="Fit") # 3
plt.title("Logarithmic Fit")
regressor = lmfit.Model(func_log) # 1
initial_guess = dict(a=1, b=.1, c=.1) # 2
results = regressor.fit(y_samp2, x=x_samp, **initial_guess)
y_fit = results.best_fit
plt.plot(x_samp, y_samp2, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()
详细信息
选择一个回归类
提供命名的、与函数域相关的初始猜测
可以从回归器对象确定推断参数。例如:
regressor.param_names
# ['decay', 'amplitude']
要执行此操作,请使用ModelResult.eval()
方法
model = results.eval
y_pred = model(x=np.array([1.5]))
注意:ExponentialModel()
遵循一个参数,它接受两个参数,其中一个是负数
另请参见接受的ExponentialGaussianModel()
通过>pip安装lmfit的库
Wolfram提供了一个用于的封闭式解决方案。它们也有类似的解决方案来安装和
我发现这比scipy的曲线拟合更有效。尤其是当你没有“接近零”的数据时。以下是一个例子:
import numpy as np
import matplotlib.pyplot as plt
# Fit the function y = A * exp(B * x) to the data
# returns (A, B)
# From: https://mathworld.wolfram.com/LeastSquaresFittingExponential.html
def fit_exp(xs, ys):
S_x2_y = 0.0
S_y_lny = 0.0
S_x_y = 0.0
S_x_y_lny = 0.0
S_y = 0.0
for (x,y) in zip(xs, ys):
S_x2_y += x * x * y
S_y_lny += y * np.log(y)
S_x_y += x * y
S_x_y_lny += x * y * np.log(y)
S_y += y
#end
a = (S_x2_y * S_y_lny - S_x_y * S_x_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
b = (S_y * S_x_y_lny - S_x_y * S_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
return (np.exp(a), b)
xs = [33, 34, 35, 36, 37, 38, 39, 40, 41, 42]
ys = [3187, 3545, 4045, 4447, 4872, 5660, 5983, 6254, 6681, 7206]
(A, B) = fit_exp(xs, ys)
plt.figure()
plt.plot(xs, ys, 'o-', label='Raw Data')
plt.plot(xs, [A * np.exp(B *x) for x in xs], 'o-', label='Fit')
plt.title('Exponential Fit Test')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
@Tomas:对。更改log的基数只需将一个常量乘以logx或logy,这不会影响r^2。这将使较小y处的值具有更大的权重。因此,最好通过y_i对卡方值的贡献进行加权。该解决方案在传统意义上的曲线拟合中是错误的。它不会最小化线性空间中残差的平方和,而是在对数空间中。如前所述,这有效地改变了点的权重——y
较小的观测值将被人为地加重。最好定义函数(线性,而不是对数变换)并使用曲线拟合器或最小化器。@santon解决了指数回归中的偏差问题。感谢您添加权重!许多/大多数人都不知道,如果您尝试只获取日志(数据)并在其中运行一行(如Excel),可能会得到非常糟糕的结果。就像我多年来一直在做的那样。当我的老师给我看这个的时候,我
import numpy as np
import matplotlib.pyplot as plt
# Fit the function y = A * exp(B * x) to the data
# returns (A, B)
# From: https://mathworld.wolfram.com/LeastSquaresFittingExponential.html
def fit_exp(xs, ys):
S_x2_y = 0.0
S_y_lny = 0.0
S_x_y = 0.0
S_x_y_lny = 0.0
S_y = 0.0
for (x,y) in zip(xs, ys):
S_x2_y += x * x * y
S_y_lny += y * np.log(y)
S_x_y += x * y
S_x_y_lny += x * y * np.log(y)
S_y += y
#end
a = (S_x2_y * S_y_lny - S_x_y * S_x_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
b = (S_y * S_x_y_lny - S_x_y * S_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
return (np.exp(a), b)
xs = [33, 34, 35, 36, 37, 38, 39, 40, 41, 42]
ys = [3187, 3545, 4045, 4447, 4872, 5660, 5983, 6254, 6681, 7206]
(A, B) = fit_exp(xs, ys)
plt.figure()
plt.plot(xs, ys, 'o-', label='Raw Data')
plt.plot(xs, [A * np.exp(B *x) for x in xs], 'o-', label='Fit')
plt.title('Exponential Fit Test')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
plt.tight_layout()
plt.show()