Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
probml
GitHub Repository: probml/pyprobml
Path: blob/master/deprecated/scripts/KLfwdReverseMixGauss.py
1192 views
1
# Visualize difference between KL(p,q) and KL(q,p) where p is a mix of two
2
# 2d Gaussians, and q is a single 2d Gaussian
3
# Author: animesh-007
4
5
6
import superimport
7
8
import numpy as np
9
import matplotlib.pyplot as plt
10
from scipy.stats import multivariate_normal
11
12
mu = np.array([[-1,-1],[1,1]])
13
14
Sigma = np.zeros((2,2,2))
15
Sigma[:,:,0] = [[1/2,1/4],[1/4,1]]
16
Sigma[:,:,1] = [[1/2,-1/4],[-1/4,1]]
17
SigmaKL = np.array([[3,2],[2,3]])
18
19
20
x1 = np.arange(-4,4.1,0.1).T
21
x2 = x1
22
23
n1 = np.size(x1)
24
n2 = np.size(x2)
25
26
f1 = np.zeros((n1,n2))
27
f2 = np.zeros((n1,n2))
28
klf = np.zeros((n1,n2))
29
kll = np.zeros((n1,n2))
30
klr = np.zeros((n1,n2))
31
32
for i in range(n1):
33
x_tile = np.tile(x1[i],(n2,1))
34
x_tile = x_tile.reshape(-1)
35
x_final = np.array([x_tile,x2])
36
x_final = x_final.T
37
f1[i,:] = multivariate_normal.pdf(x_final,mu[0,:],Sigma[:,:,0])
38
f2[i,:] = multivariate_normal.pdf(x_final,mu[1,:],Sigma[:,:,1])
39
klf[i,:] = multivariate_normal.pdf(x_final,[0,0],SigmaKL)
40
kll[i,:] = multivariate_normal.pdf(x_final,mu[0,:],Sigma[:,:,0]*0.6)
41
klr[i,:] = multivariate_normal.pdf(x_final,mu[1,:],Sigma[:,:,1]*0.6)
42
43
44
f = f1 + f2
45
46
plots = [klf, kll, klr]
47
48
fig, ax = plt.subplots(1,3,figsize=(8,8))
49
for axi, plot_ in zip(ax.flat,plots):
50
axi.axis('off')
51
axi.contour(x1, x2, f, colors='b', zorder=1)
52
axi.contour(x1,x2,plot_, colors='r',zorder=10)
53
54
fig.savefig('../figures/klfwdzrevmixgauss.pdf', dpi=300)
55
plt.show()
56
57