在 python 中使用 levenberg-marquardt 算法对数据应用幂拟合

Apply power fit to data by using levenberg-marquardt algorithm in python

大家好! 我是 python 和数据分析的初学者,在为我的数据拟合幂函数时遇到了问题。 Here I plotted my dataset as a scatterplot

我想绘制指数约为 -1 的幂函数,但在我应用 levenberg-marquardt 方法后,使用 python、I get the following faulty image. 中的 lmfit 库,我尝试修改初始参数, 但它没有帮助。

这是我的代码:

%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from lmfit import minimize, Parameters, Parameter, report_fit
be = pd.read_table('...', 
               skipinitialspace=True,
               names = ["CoM", "slope", "slope2"])

x=be["CoM"]
data=be["slope"]




def fcn2min(params, x, data):
n2 = params['n2'].value
n1 = params['n1'].value

model = n1 * x ** n2
return model - data #that's what you want to minimize

# create a set of Parameters
# 'value' is the initial condition
params = Parameters() 
params.add('n2', value= -1.00)
params.add('n1',value= 23.0)

# do fit, here with leastsq model
result = minimize(fcn2min, params, args=(be["CoM"],be["slope"]))

#calculate final result
final = data + result.residual
resid = result.residual

# write error report
report_fit(result)

#plot results

xplot = x
yplot = result.params['n1'].value * x ** result.params['n2'].value


plt.figure(figsize=(15,6))
plt.ylabel('OD-slope',fontsize=18, color='blue')
plt.xlabel('CoM height_Sz  [m]',fontsize=18, color='blue')

plt.plot(be["CoM"],be["slope"],"o", label="slope_flat")
plt.plot(be["CoM"],be["slope2"],"+",color='r', label="slope_curv")
plt.plot(xplot,yplot)
plt.legend()

plt.savefig('plot2')

plt.show()

我不是很明白这是什么问题,所以如果你有任何意见,非常感谢。

很难说出问题是什么。在我看来,拟合已经完成并且拟合得相当好,但您没有提供拟合统计数据或参数报告。

如果您询问的是 "COM" 数组的所有绿线(最合适?),这几乎可以肯定是因为起始 x 轴 "height_Sz" 数据未排序为严格递增。这对于拟合来说没问题,但是用一条线绘制 X-Y 迹线预计数据是有序的。