%pylab inline import numpy as np from matplotlib import pyplot as plt def pdf(x, mu, sigma): """ Calculates the normal distribution's probability density function (PDF). """ term1 = 1.0 / ( math.sqrt(2*np.pi) * sigma ) term2 = np.exp( -0.5 * ( (x-mu)/sigma )**2 ) return term1 * term2 # generating some sample data x = np.arange(0, 100, 0.05) # probability density functions pdf1 = pdf(x, mu=4, sigma=1) pdf2 = pdf(x, mu=10, sigma=1) # Class conditional densities (likelihoods) plt.plot(x, pdf1) plt.plot(x, pdf2) plt.title('Class conditional densities (likelihoods)') plt.ylabel('p(x)') plt.xlabel('random variable x') plt.legend(['p(x|w_1) ~ N(4,1)', 'p(x|w_2) ~ N(10,1)'], loc='upper right') plt.ylim([0,0.5]) plt.xlim([0,20]) plt.show() def posterior(likelihood, prior): """ Calculates the posterior probability (after Bayes Rule) without the scale factor p(x) (=evidence). """ return likelihood * prior # probability density functions posterior1 = posterior(pdf(x, mu=4, sigma=1), 0.5) posterior2 = posterior(pdf(x, mu=10, sigma=1), 0.5) # Class conditional densities (likelihoods) plt.plot(x, posterior1) plt.plot(x, posterior2) plt.title('Posterior Probabilities w. Decision Boundary') plt.ylabel('P(w)') plt.xlabel('random variable x') plt.legend(['P(w_1|x)', 'p(w_2|X)'], loc='upper right') plt.ylim([0,0.5]) plt.xlim([0,20]) plt.axvline(7, color='r', alpha=0.8, linestyle=':', linewidth=2) plt.annotate('R1', xy=(4, 0.3), xytext=(4, 0.3)) plt.annotate('R2', xy=(10, 0.3), xytext=(10, 0.3)) plt.show() # Parameters mu_1 = 4 mu_2 = 10 sigma_1_sqr = 1 sigma_2_sqr = 1 # Generating 10 random samples drawn from a Normal Distribution for class 1 & 2 x1_samples = sigma_1_sqr**0.5 * np.random.randn(10) + mu_1 x2_samples = sigma_1_sqr**0.5 * np.random.randn(10) + mu_2 y = [0 for i in range(10)] # Plotting sample data with a decision boundary plt.scatter(x1_samples, y, marker='o', color='green', s=40, alpha=0.5) plt.scatter(x2_samples, y, marker='^', color='blue', s=40, alpha=0.5) plt.title('Classifying random example data from 2 classes') plt.ylabel('P(x)') plt.xlabel('random variable x') plt.legend(['w_1', 'w_2'], loc='upper right') plt.ylim([-0.1,0.1]) plt.xlim([0,20]) plt.axvline(7, color='r', alpha=0.8, linestyle=':', linewidth=2) plt.annotate('R1', xy=(4, 0.05), xytext=(4, 0.05)) plt.annotate('R2', xy=(10, 0.05), xytext=(10, 0.05)) plt.show() w1_as_w2, w2_as_w1 = 0, 0 for x1,x2 in zip(x1_samples, x2_samples): if x1 >= 7: w1_as_w2 += 1 if x2 < 7: w2_as_w1 += 1 emp_err = (w1_as_w2 + w2_as_w1) / float(len(x1_samples) + len(x2_samples)) print('Empirical Error: {}%'.format(emp_err * 100))