DimKoim
DimKoim

Reputation: 1044

Probability density function numpy histogram/scipy stats

We have the arraya=range(10). Using numpy.histogram:

hist,bins=numpy.histogram(a,bins=(np.max(a)-np.min(a))/1, range=np.min(a),np.max(a)),density=True)

According to numpy tutorial:

If density=True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1.

The result is:

array([ 0.1,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1,  0.2])

I try to do the same using scipy.stats:

mean = np.mean(a)
sigma = np.std(a)
norm.pdf(a, mean, sigma)

However the result is different:

array([ 0.04070852,  0.06610774,  0.09509936,  0.12118842,  0.13680528,0.13680528,  0.12118842,  0.09509936,  0.06610774,  0.04070852])

I want to know why.

Update:I would like to set a more general question. How can we have the probability density function of an array without using numpy.histogram for density=True ?

Upvotes: 4

Views: 12684

Answers (3)

user2888944
user2888944

Reputation: 11

Plotting a Continuous Probability Function(PDF) from a Histogram – Solved in Python. refer this blog for detailed explanation. (http://howdoudoittheeasiestway.blogspot.com/2017/09/plotting-continuous-probability.html) Else you can use the code below.

n, bins, patches = plt.hist(A, 40, histtype='bar')
plt.show()
n = n/len(A)
n = np.append(n, 0)
mu = np.mean(n)
sigma = np.std(n)
plt.bar(bins,n, width=(bins[len(bins)-1]-bins[0])/40)
y1= (1/(sigma*np.sqrt(2*np.pi))*np.exp(-(bins - mu)**2 /(2*sigma**2)))*0.03
plt.plot(bins, y1, 'r--', linewidth=2)
plt.show()

Upvotes: 1

farhawa
farhawa

Reputation: 10398

You can't compare numpy.histogram() and scipy.stats.norm() for this sample reason:

scipy.stats.norm() is A normal continuous random variable while numpy.histogram() deal with sequences (discontinuous)

Upvotes: 1

jtitusj
jtitusj

Reputation: 3086

If density=True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1.

The "normalized" there does not mean that it will be transformed using a Normal Distribution. It simply says that each value in the bin will be divided by the total number of entries so that the total density would be equal to 1.

Upvotes: 2

Related Questions