gpt4 book ai didi

python - 拟合高斯函数

转载 作者:IT老高 更新时间:2023-10-28 20:24:35 25 4
gpt4 key购买 nike

我有一个直方图(见下文),我正在尝试找出平均值和标准差以及适合我的直方图曲线的代码。我认为 SciPy 或 matplotlib 中有些东西可以提供帮助,但我尝试过的每个示例都不起作用。

import matplotlib.pyplot as plt
import numpy as np

with open('gau_b_g_s.csv') as f:
v = np.loadtxt(f, delimiter= ',', dtype="float", skiprows=1, usecols=None)

fig, ax = plt.subplots()

plt.hist(v, bins=500, color='#7F38EC', histtype='step')

plt.title("Gaussian")
plt.axis([-1, 2, 0, 20000])

plt.show()

最佳答案

看看this answer用于将任意曲线拟合到数据。基本上你可以使用scipy.optimize.curve_fit以适合您想要的数据的任何功能。下面的代码展示了如何将高斯拟合到一些随机数据(归功于 this SciPy-User 邮件列表帖子)。

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

# Define some test data which is close to Gaussian
data = numpy.random.normal(size=10000)

hist, bin_edges = numpy.histogram(data, density=True)
bin_centres = (bin_edges[:-1] + bin_edges[1:])/2

# Define model function to be used to fit to the data above:
def gauss(x, *p):
A, mu, sigma = p
return A*numpy.exp(-(x-mu)**2/(2.*sigma**2))

# p0 is the initial guess for the fitting coefficients (A, mu and sigma above)
p0 = [1., 0., 1.]

coeff, var_matrix = curve_fit(gauss, bin_centres, hist, p0=p0)

# Get the fitted curve
hist_fit = gauss(bin_centres, *coeff)

plt.plot(bin_centres, hist, label='Test data')
plt.plot(bin_centres, hist_fit, label='Fitted data')

# Finally, lets get the fitting parameters, i.e. the mean and standard deviation:
print 'Fitted mean = ', coeff[1]
print 'Fitted standard deviation = ', coeff[2]

plt.show()

关于python - 拟合高斯函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11507028/

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