In [1]:
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
np.set_printoptions(precision=4, suppress=True)
sns.set_context('notebook')
%matplotlib inline
In [2]:
theta = 1
y = np.linspace(0, 10, 100)
f = theta * np.exp(-theta * y)
# plot function
plt.plot(y, f)
plt.xlabel('y')
plt.ylabel('f')
plt.show()
In [3]:
# try several parameters
theta = [1, .5, .25]
y = np.linspace(0, 10, 100)
# for each parameter value
for t in theta:
f = t * np.exp( - t * y)
plt.plot(y, f)
plt.xlabel('y')
plt.ylabel('f')
plt.legend(theta)
plt.show()
In [4]:
n = 100
theta = 1
# simulate data
y = np.random.exponential(1 / theta, n)
# plot data
plt.hist(y, bins=10, normed=True)
plt.xlabel(r'$y_i$')
plt.ylabel(r'$\hat{f}$')
plt.show()
MLE estimator is
$$\hat{\theta}=\frac{n}{\sum_{i=1}^{n}y_{i}}=\overline{y}^{-1}$$
In [5]:
# sample size
n = int(1e2)
# true parameter value
theta = 1
# simulate data
y = np.sort(np.random.exponential(1 / theta, n))
# MLE estimator
theta_hat = n / np.sum(y)
print('Estimate is: theta = ', theta_hat)
# function of exponential density
f = lambda theta: theta * np.exp( - theta * y)
# plot results
plt.hist(y, bins = 10, normed = True, alpha = .2, lw = 0)
plt.plot(y, f(theta), c = 'black')
plt.plot(y, f(theta_hat), c = 'red')
plt.xlabel(r'$y_i$')
plt.ylabel(r'$\hat{f}$')
plt.legend(('True', 'Fitted','Histogram'))
plt.show()