Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
probml
GitHub Repository: probml/pyprobml
Path: blob/master/deprecated/scripts/bimodal_dist_plot.py
1192 views
1
# Bimodal distribution (mixture of two 1d Gaussians)
2
# Based on https://github.com/probml/pmtk3/blob/master/demos/bimodalDemo.m
3
4
5
import superimport
6
7
import numpy as np
8
import matplotlib.pyplot as plt
9
import pyprobml_utils as pml
10
11
12
from scipy.stats import norm
13
14
# Define two normal distrubutions and their corresponding weights.
15
mu = [0, 2]
16
sigma = [1, 0.05]
17
n = [norm(loc=mu[i], scale=sigma[i]) for i in range(2)]
18
w = [0.5, 0.5]
19
20
# Define a set of x points for graphing.
21
xs = np.linspace(-2, 2*mu[1], 600)
22
23
# Combine the two distributions by their weights, evaluated at the x points.
24
p = sum(w[i] * n[i].pdf(xs) for i in range(2))
25
26
# Calculate the mean of the final distribution.
27
mean_p = np.mean(xs * p)
28
29
# Plot the final distribution and its mean.
30
linewidth = 3
31
plt.figure()
32
plt.plot(xs, p, 'black', linewidth=linewidth)
33
plt.vlines(mean_p, ymin=0, ymax=max(p), color='red', linewidth=linewidth)
34
pml.savefig('bimodalSpike.pdf')
35
plt.show()
36
37
38
# Another example, with two modes
39
mu = [0, 2]
40
sigma = [0.5, 0.5]
41
n = [norm(loc=mu[i], scale=sigma[i]) for i in range(2)]
42
w = [0.5, 0.5]
43
xs = np.linspace(-2, 2*mu[1], 600)
44
p = sum(w[i] * n[i].pdf(xs) for i in range(2))
45
46
plt.figure()
47
linewidth = 3
48
plt.plot(xs, p, 'black', linewidth=linewidth)
49
pml.savefig('bimodalDistribution.pdf')
50
plt.show()
51
52