直方图与python拟合 [英] Histogram fitting with python

查看:271
本文介绍了直方图与python拟合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在冲浪,但是没有找到执行以下操作的正确方法.

I've been surfing but haven't found the correct method to do the following.

我用matplotlib完成了直方图:

I have a histogram done with matplotlib:

hist, bins, patches = plt.hist(distance, bins=100, normed='True')

从图中可以看出,分布或多或少是指数分布(泊松分布).考虑到我的hist和bins数组,如何做最合适的?

From the plot, I can see that the distribution is more or less an exponential (Poisson distribution). How can I do the best fitting, taking into account my hist and bins arrays?

更新

我正在使用以下方法:

x = np.float64(bins) # Had some troubles with data types float128 and float64
hist = np.float64(hist)
myexp=lambda x,l,A:A*np.exp(-l*x)
popt,pcov=opt.curve_fit(myexp,(x[1:]+x[:-1])/2,hist)

但是我明白了

---> 41 plt.plot(stats.expon.pdf(np.arange(len(hist)),popt),'-')

ValueError: operands could not be broadcast together with shapes (100,) (2,)

推荐答案

您所描述的是指数形式分布,并且您要根据数据中观察到的概率密度来估计指数分布的参数.可以使用MLE(最大似然估计)代替正确的方法,而不是使用非线性回归方法(假定残差误差是高斯分布的).

What you described is a form of exponential distribution, and you want to estimate the parameters of the exponential distribution, given the probability density observed in your data. Instead of using non-linear regression method (which assumes the residue errors are Gaussian distributed), one correct way is arguably a MLE (maximum likelihood estimation).

scipy在其stats库中提供了大量连续分布,并且MLE通过.fit()方法实现.当然,指数分布是:

scipy provides a large number of continuous distributions in its stats library, and the MLE is implemented with the .fit() method. Of course, exponential distribution is there:

In [1]:

import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
%matplotlib inline
In [2]:
#generate data 
X = ss.expon.rvs(loc=0.5, scale=1.2, size=1000)

#MLE
P = ss.expon.fit(X)
print P
(0.50046056920696858, 1.1442947648425439)
#not exactly 0.5 and 1.2, due to being a finite sample

In [3]:
#plotting
rX = np.linspace(0,10, 100)
rP = ss.expon.pdf(rX, *P)
#Yup, just unpack P with *P, instead of scale=XX and shape=XX, etc.
In [4]:

#need to plot the normalized histogram with `normed=True`
plt.hist(X, normed=True)
plt.plot(rX, rP)
Out[4]:

您的distance将在此处替换X.

这篇关于直方图与python拟合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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