python直方图拟合曲线_直方图与python拟合

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

I have a histogram done with matplotlib:

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

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?

UPDATE

I am using the following approach:

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)

But I get

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

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

解决方案

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 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]:

Your distance will replace X here.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值