-
Notifications
You must be signed in to change notification settings - Fork 0
/
learnGaussian.py
198 lines (150 loc) · 5.71 KB
/
learnGaussian.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
def new_idea():
def bivariate_gaussian(pos, mu, Sigma):
"""
Get rid of the einsum function
:param pos: 2-D
:param mu: 2-D
:param Sigma: 2x2
:return:
"""
assert mu.shape[0] == 2
Sigma_det = np.linalg.det(Sigma)
Sigma_inv = np.linalg.inv(Sigma)
N = np.sqrt((2 * np.pi) ** 2 * Sigma_det)
fac = np.sum(np.dot((pos-mu), Sigma_inv)*(pos-mu), axis=1)
return np.exp(-fac / 2) / N
# Our 2-dimensional distribution will be over variables X and Y
N = 60
X = np.linspace(0, 60, N)
Y = np.linspace(0, 60, N)
X, Y = np.meshgrid(X, Y)
# Mean vector and covariance matrix
mu = np.array([30., 31.])
Sigma = np.array([[20., 1.5], [0, 15]])
# Pack X and Y into a single 3-dimensional array
pos = np.empty(X.shape + (2,))
pos[:, :, 0] = X
pos[:, :, 1] = Y
pos = pos.reshape((N*N, 2))
# The distribution on the variables X, Y packed into pos.
Z = 10 * bivariate_gaussian(pos, mu, Sigma)
Z = np.reshape(Z, (N, N))
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z, rstride=3, cstride=3, linewidth=1, antialiased=True,
cmap=cm.viridis)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-0.15, cmap=cm.viridis)
# Adjust the limits, ticks and view angle
ax.set_zlim(-0.15, 0.2)
ax.set_zticks(np.linspace(0, 0.2, 5))
ax.view_init(27, -21)
plt.show()
def numpy_version():
# Our 2-dimensional distribution will be over variables X and Y
N = 60
X = np.linspace(0, 60, N)
Y = np.linspace(0, 60, N)
X, Y = np.meshgrid(X, Y)
# Mean vector and covariance matrix
mu = np.array([30., 31.])
Sigma = np.array([[ 20. , 1.5], [0, 15]])
# Pack X and Y into a single 3-dimensional array
pos = np.empty(X.shape + (2,))
pos[:, :, 0] = X
pos[:, :, 1] = Y
def multivariate_gaussian(pos, mu, Sigma):
"""Return the multivariate Gaussian distribution on array pos.
pos is an array constructed by packing the meshed arrays of variables
x_1, x_2, x_3, ..., x_k into its _last_ dimension.
"""
n = mu.shape[0]
Sigma_det = np.linalg.det(Sigma)
Sigma_inv = np.linalg.inv(Sigma)
N = np.sqrt((2*np.pi)**n * Sigma_det)
# This einsum call calculates (x-mu)T.Sigma-1.(x-mu) in a vectorized
# way across all the input variables.
fac = np.einsum('...k,kl,...l->...', pos-mu, Sigma_inv, pos-mu)
return np.exp(-fac / 2) / N
# The distribution on the variables X, Y packed into pos.
Z = 10*multivariate_gaussian(pos, mu, Sigma)
print(Z.shape)
# Create a surface plot and projected filled contour plot under it.
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z, rstride=3, cstride=3, linewidth=1, antialiased=True,
cmap=cm.viridis)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-0.15, cmap=cm.viridis)
# Adjust the limits, ticks and view angle
ax.set_zlim(-0.15,0.2)
ax.set_zticks(np.linspace(0, 0.2, 5))
ax.view_init(27, -21)
plt.show()
def torch_version():
import torch
# Our 2-dimensional distribution will be over variables X and Y
N = 60
X = np.linspace(0, 60, N)
Y = np.linspace(0, 60, N)
X, Y = np.meshgrid(X, Y)
# Mean vector and covariance matrix
mu = np.array([30., 31.])
Sigma = np.array([[20., 1.5], [0, 15]])
# Pack X and Y into a single 3-dimensional array
pos = np.empty(X.shape + (2,))
pos[:, :, 0] = X
pos[:, :, 1] = Y
pos_reshape = np.reshape(pos, (N*N, 2))
mu_torch = torch.Tensor(mu)
sigma_torch = torch.Tensor(Sigma)
pos_torch = torch.Tensor(pos)
def multivariate_gaussian(pos, mu, Sigma):
"""Return the multivariate Gaussian distribution on array pos.
pos is an array constructed by packing the meshed arrays of variables
x_1, x_2, x_3, ..., x_k into its _last_ dimension.
"""
pi = 3.14159265359
n = mu.shape[0]
assert n == 2
Sigma_det = torch.det(Sigma)
Sigma_inv = torch.inverse(Sigma)
N = torch.sqrt((2*pi)**n * Sigma_det)
# This einsum call calculates (x-mu)T.Sigma-1.(x-mu) in a vectorized
# way across all the input variables.
fac = torch.einsum('...k,kl,...l->...', [pos-mu, Sigma_inv, pos-mu])
return torch.exp(-fac / 2) / N
def bivariate_gaussian(pos, mu, Sigma):
"""
Get rid of the einsum function
"""
pi = 3.14159265359
assert mu.shape[0] == 2
Sigma_det = torch.det(Sigma)
Sigma_inv = torch.inverse(Sigma)
N = torch.sqrt((2 * pi) ** 2 * Sigma_det)
fac = torch.sum(torch.mm((pos - mu), Sigma_inv) * (pos - mu), dim=1)
return torch.exp(-fac / 2) / N
# The distribution on the variables X, Y packed into pos.
pos_torch = torch.Tensor(pos_reshape)
Z = 10 * bivariate_gaussian(pos_torch, mu_torch, sigma_torch)
print(Z.shape)
Z = Z.data.numpy()
Z = np.reshape(Z, (N, N))
# Create a surface plot and projected filled contour plot under it.
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z, rstride=3, cstride=3, linewidth=1, antialiased=True,
cmap=cm.viridis)
cset = ax.contourf(X, Y, Z, zdir='z', offset=-0.15, cmap=cm.viridis)
# Adjust the limits, ticks and view angle
ax.set_zlim(-0.15, 0.2)
ax.set_zticks(np.linspace(0, 0.2, 5))
ax.view_init(27, -21)
plt.show()
if __name__ == '__main__':
# numpy_version()
torch_version()
# new_idea()