如何在python中拟合高斯曲线? [英] How can I fit a gaussian curve in python?

查看:860
本文介绍了如何在python中拟合高斯曲线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给了我一个数组,当我绘制它时,我得到了带有一些噪声的高斯形状。我想适合高斯人。这是我已经拥有的,但是当我绘制它时,我没有得到拟合的高斯,而是得到一条直线。我已经尝试了许多不同的方法,但我只是想不通。

  random_sample = norm.rvs(h) 

参数= norm.fit(h)

fit_pdf = norm.pdf(f,loc = parameters [0],scale = parameters [1])$ ​​b
$ b normal_pdf = norm.pdf(f)

plt.plot(f,fitted_pdf, green)
plt.plot(f,normal_pdf, red)
plt.plot(f,h)
plt.show()

解决方案

您可以使用


蓝色框是数据的直方图,绿线是具有拟合参数的高斯。


I'm given an array and when I plot it I get a gaussian shape with some noise. I want to fit the gaussian. This is what I already have but when I plot this I do not get a fitted gaussian, instead I just get a straight line. I've tried this many different ways and I just can't figure it out.

random_sample=norm.rvs(h)

parameters = norm.fit(h)

fitted_pdf = norm.pdf(f, loc = parameters[0], scale = parameters[1])

normal_pdf = norm.pdf(f)

plt.plot(f,fitted_pdf,"green")
plt.plot(f, normal_pdf, "red")
plt.plot(f,h)
plt.show()

解决方案

You can use fit from scipy.stats.norm as follows:

import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt

data = np.random.normal(loc=5.0, scale=2.0, size=1000)
mean,std=norm.fit(data)

norm.fit tries to fit the parameters of a normal distribution based on the data. And indeed in the example above mean is approximately 5 and std is approximately 2.

In order to plot it, you can do:

plt.hist(data, bins=30, normed=True)
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
y = norm.pdf(x, mean, std)
plt.plot(x, y)
plt.show()

The blue boxes are the histogram of your data, and the green line is the Gaussian with the fitted parameters.

这篇关于如何在python中拟合高斯曲线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆