gpt4 book ai didi

python - 拟合高斯分布,必须使用 python 中提供的均值

转载 作者:行者123 更新时间:2023-12-01 07:00:58 26 4
gpt4 key购买 nike

无论如何,有没有适合高斯的方法,我不仅提供平均值的建议或最佳猜测,而且必须接受它并调整其他参数才能使其工作?我知道这不会给我提供最适合的数据,但这不是必需的。

最佳答案

@BenedictWilkinsAI 建议是最简单的方法,用固定值代替平均值编写方程。然而,如果您想使用编程解决方案,这里有一个图形化的 Python 拟合器,它允许正常(双关语)和固定均值高斯峰值方程拟合。当使用固定的平均参数值 9.0 时,拟合效果明显较差 - 正如预期的那样。此外,curve_fit() 会发出警告,指出它无法计算协方差矩阵,因为均值参数不能变化。

plot1

plot2

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

xData = numpy.array([5.357, 5.797, 5.936, 6.161, 6.697, 6.731, 6.775, 8.442, 9.861])
yData = numpy.array([0.376, 0.874, 1.049, 1.327, 2.054, 2.077, 2.138, 4.744, 7.104])

# normally fitted mean is 10.67571675
# set this value to None to fit normally, else
# set to the value of the fixed mean
fixedMean = 9.0

def func(x, a, b, c): # Gaussian peak equation
if fixedMean:
b = fixedMean
return a * numpy.exp(-0.5 * numpy.power((x-b) / c, 2.0))


# these are the same as the scipy defaults except for the fixed mean
if fixedMean:
initialParameters = numpy.array([1.0, fixedMean, 1.0])
else:
initialParameters = numpy.array([1.0, 1.0, 1.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, p0=initialParameters)

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()


##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
axes = f.add_subplot(111)

# first the raw data as a scatter plot
axes.plot(xData, yData, 'D')

# create data for the fitted equation plot
xModel = numpy.linspace(min(xData), max(xData))
yModel = func(xModel, *fittedParameters)

# now the model as a line plot
axes.plot(xModel, yModel)

axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label

plt.show()
plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)

关于python - 拟合高斯分布,必须使用 python 中提供的均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com