用python将数据拟合到自定义模型

2024-06-12 22:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,所以我相当习惯python,但这是我第一次使用python进行数据分析,我想知道您是否可以对我遇到的一个问题有所了解。在

我需要将大约4000个不同的曲线拟合到以下函数: b+e*A*(1.19104*(10**-16))*((x*(10**-9))**-5)*((-1+np.exp(0.0143878/(T*x*(10**-9))))**-1) 在这个函数中,我想把b,e和A限制在每个曲线图的特定值,并且变量T的值要根据数据移动。在

我试着用scipy优化,但我不知道如何用它来保存参数。在

我尝试使用pyastrophy functfit,但其中一个原因是效率极低(或者我的代码是idk),而且我得到的数据与我所得到的数据不符。在

最后,我正在尝试使用lmfit,但是我这里的代码似乎所有的参数都与猜测保持一致,并且一点都没有变化。我不知道该怎么继续。 我当前的代码是这样的。。。在

def bbnm(x,b,e,T,A):
   y = b+e*A*(1.19104*(10**-16))*((x*(10**-9))**-5)*((-1+np.exp(0.0143878/(T*x*(10**-9))))**-1)
   return y     

params = bbmodel.make_params(b=0,e=.99,T=5100,A=wgeometry)
params['b'].vary = False
params['e'].vary = False
params['A'].vary = False
params['T'].vary = True
bb = bbmodel.fit(power[1465:2510],params,x=wavelength[1465:2510])

Tags: 数据函数代码false参数npscipyparams
1条回答
网友
1楼 · 发布于 2024-06-12 22:11:35

下面的代码将scipy的曲线拟合参数限制在指定的范围内。在本例中,第一个参数的边界为+/-无穷大(无界),第二个参数的边界为+/-100,但拟合参数在边界内并正常拟合,第三个参数受其边界限制。在

import numpy
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

xData = numpy.array([5.0, 6.1, 7.2, 8.3, 9.4])
yData = numpy.array([ 10.0,  18.4,  20.8,  23.2,  35.0])


def standardFunc(data, a, b, c):
    return a * data + b * data**2 + c


# some initial parameter values - must be within bounds
initialParameters = numpy.array([1.0, 1.0, 1.0])

# bounds on parameters - initial parameters must be within these
lowerBounds = (-numpy.Inf, -100.0, -5.0)
upperBounds = (numpy.Inf, 100.0, 5.0)
parameterBounds = [lowerBounds, upperBounds]

fittedParameters, pcov = curve_fit(standardFunc, xData, yData, initialParameters, bounds = parameterBounds)

# values for display of fitted function
a, b, c = fittedParameters

# for plotting the fitting results
xPlotData = numpy.linspace(min(xData), max(xData), 50)
y_plot = standardFunc(xPlotData, a, b, c)

plt.plot(xData, yData, 'D') # plot the raw data as a scatterplot
plt.plot(xPlotData, y_plot) # plot the equation using the fitted parameters
plt.show()

print('fitted parameters:', fittedParameters)

相关问题 更多 >