There have been quite a few posts on handling the lognorm
distribution with Scipy but i still dont get the hang of it.
The 2 parameter lognormal is usually described by the parameters mu
and sigma
which corresponds to Scipys loc=0
and sigma=shape
, mu=np.log(scale)
.
At scipy, lognormal distribution - parameters, we can read how to generate a lognorm(mu,sigma)
sample using the exponential of a random distribution. Now lets try something else:
A)
Whats the problem in creating a lognorm directly:
# lognorm(mu=10,sigma=3)
# so shape=3, loc=0, scale=np.exp(10) ?
x=np.linspace(0.01,20,200)
sample_dist = sp.stats.lognorm.pdf(x, 3, loc=0, scale=np.exp(10))
shape, loc, scale = sp.stats.lognorm.fit(sample_dist, floc=0)
print shape, loc, scale
print np.log(scale), shape # mu and sigma
# last line: -7.63285693379 0.140259699945 # not 10 and 3
B)
I use the return values of a fit to create a fitted distribution. But again im doing something wrong apparently:
samp=sp.stats.lognorm(0.5,loc=0,scale=1).rvs(size=2000) # sample
param=sp.stats.lognorm.fit(samp) # fit the sample data
print param # does not coincide with shape, loc, scale above!
x=np.linspace(0,4,100)
pdf_fitted = sp.stats.lognorm.pdf(x, param[0], loc=param[1], scale=param[2]) # fitted distribution
pdf = sp.stats.lognorm.pdf(x, 0.5, loc=0, scale=1) # original distribution
plt.plot(x,pdf_fitted,'r-',x,pdf,'g-')
plt.hist(samp,bins=30,normed=True,alpha=.3)
See Question&Answers more detail:
os