forked from IceLab-X/MiniGP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cigp_dkl.py
273 lines (219 loc) · 9.75 KB
/
cigp_dkl.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# Conditional independent Gaussian process (CIGP) for vector output regression based on pytorch
# CIGP use a single kernel for each output. Thus the log likelihood is simply a sum of the log likelihood of each output.
#
# v10: A stable version. improve over the v02 version to fix nll bug; adapt to torch 1.11.0.
#
# Author: Wei W. Xing (wxing.me)
# Email: wayne.xingle@gmail.com
# Date: 2022-03-23
# %%
import torch
import torch.nn as nn
import numpy as np
from matplotlib import pyplot as plt
print(torch.__version__)
# I use torch (1.11.0) for this work. lower version may not work.
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # Fixing strange error if run in MacOS
JITTER = 1e-6
EPS = 1e-10
PI = 3.1415
class cigp(nn.Module):
def __init__(self, X, Y, normal_y_mode=0):
# normal_y_mode = 0: normalize Y by combing all dimension.
# normal_y_mode = 1: normalize Y by each dimension.
super(cigp, self).__init__()
#normalize X independently for each dimension
self.Xmean = X.mean(0)
self.Xstd = X.std(0)
self.X = (X - self.Xmean.expand_as(X)) / (self.Xstd.expand_as(X) + EPS)
if normal_y_mode == 0:
# normalize y all together
self.Ymean = Y.mean()
self.Ystd = Y.std()
self.Y = (Y - self.Ymean.expand_as(Y)) / (self.Ystd.expand_as(Y) + EPS)
elif normal_y_mode == 1:
# option 2: normalize y by each dimension
self.Ymean = Y.mean(0)
self.Ystd = Y.std(0)
self.Y = (Y - self.Ymean.expand_as(Y)) / (self.Ystd.expand_as(Y) + EPS)
# GP hyperparameters
self.log_beta = nn.Parameter(torch.ones(1) * 0) # a large noise by default. Smaller value makes larger noise variance.
self.log_length_scale = nn.Parameter(torch.zeros(X.size(1))) # ARD length scale
self.log_scale = nn.Parameter(torch.zeros(1)) # kernel scale
# X_dim = X.size(1)
self.dkl_nn = nn.Sequential(nn.Linear(self.X.size(1), 8),
nn.Sigmoid(),
nn.Linear(8, 16),
nn.Sigmoid(),
nn.Linear(16, self.Y.size(1)) )
# define kernel function
def kernel(self, X1, X2):
# the common RBF kernel
X1 = X1 / self.log_length_scale.exp()
X2 = X2 / self.log_length_scale.exp()
# X1_norm2 = X1 * X1
# X2_norm2 = X2 * X2
X1_norm2 = torch.sum(X1 * X1, dim=1).view(-1, 1)
X2_norm2 = torch.sum(X2 * X2, dim=1).view(-1, 1)
K = -2.0 * X1 @ X2.t() + X1_norm2.expand(X1.size(0), X2.size(0)) + X2_norm2.t().expand(X1.size(0), X2.size(0)) #this is the effective Euclidean distance matrix between X1 and X2.
K = self.log_scale.exp() * torch.exp(-0.5 * K)
return K
def kernel_matern3(self, x1, x2):
"""
latex formula:
\sigma ^2\left( 1+\frac{\sqrt{3}d}{\rho} \right) \exp \left( -\frac{\sqrt{3}d}{\rho} \right)
:param x1: x_point1
:param x2: x_point2
:return: kernel matrix
"""
const_sqrt_3 = torch.sqrt(torch.ones(1) * 3)
x1 = x1 / self.log_length_matern3.exp()
x2 = x2 / self.log_length_matern3.exp()
distance = const_sqrt_3 * torch.cdist(x1, x2, p=2)
k_matern3 = self.log_coe_matern3.exp() * (1 + distance) * (- distance).exp()
return k_matern3
def kernel_matern5(self, x1, x2):
"""
latex formula:
\sigma ^2\left( 1+\frac{\sqrt{5}}{l}+\frac{5r^2}{3l^2} \right) \exp \left( -\frac{\sqrt{5}distance}{l} \right)
:param x1: x_point1
:param x2: x_point2
:return: kernel matrix
"""
const_sqrt_5 = torch.sqrt(torch.ones(1) * 5)
x1 = x1 / self.log_length_matern5.exp()
x2 = x2 / self.log_length_matern5.exp()
distance = const_sqrt_5 * torch.cdist(x1, x2, p=2)
k_matern5 = self.log_coe_matern5.exp() * (1 + distance + distance ** 2 / 3) * (- distance).exp()
return k_matern5
def forward(self, Xte):
n_test = Xte.size(0)
Xte = ( Xte - self.Xmean.expand_as(Xte) ) / self.Xstd.expand_as(Xte)
Xte = self.dkl_nn(Xte)
X = self.dkl_nn(self.X)
Sigma = self.kernel(X, X) + self.log_beta.exp().pow(-1) * torch.eye(X.size(0)) \
+ JITTER * torch.eye(X.size(0))
kx = self.kernel(X, Xte)
L = torch.cholesky(Sigma)
LinvKx,_ = torch.triangular_solve(kx, L, upper = False)
# option 1
mean = kx.t() @ torch.cholesky_solve(self.Y, L) # torch.linalg.cholesky()
var_diag = self.kernel(Xte, Xte).diag().view(-1, 1) \
- (LinvKx**2).sum(dim = 0).view(-1, 1)
# add the noise uncertainty
var_diag = var_diag + self.log_beta.exp().pow(-1)
# de-normalized
mean = mean * self.Ystd.expand_as(mean) + self.Ymean.expand_as(mean)
var_diag = var_diag.expand_as(mean) * self.Ystd**2
return mean, var_diag
def negative_log_likelihood(self):
X = self.dkl_nn(self.X)
y_num, y_dimension = self.Y.shape
Sigma = self.kernel(X, X) + self.log_beta.exp().pow(-1) * torch.eye(
X.size(0)) + JITTER * torch.eye(X.size(0))
L = torch.linalg.cholesky(Sigma)
#option 1 (use this if torch supports)
Gamma,_ = torch.triangular_solve(self.Y, L, upper = False)
#option 2
# gamma = L.inverse() @ Y # we can use this as an alternative because L is a lower triangular matrix.
nll = 0.5 * (Gamma ** 2).sum() + L.diag().log().sum() * y_dimension \
+ 0.5 * y_num * torch.log(2 * torch.tensor(PI)) * y_dimension
return nll
def train_adam(self, niteration=10, lr=0.1):
# adam optimizer
# uncommont the following to enable
optimizer = torch.optim.Adam(self.parameters(), lr=lr)
optimizer.zero_grad()
for i in range(niteration):
optimizer.zero_grad()
# self.update()
loss = self.negative_log_likelihood()
loss.backward()
optimizer.step()
# print('loss_nll:', loss.item())
# print('iter', i, ' nll:', loss.item())
print('iter', i, 'nll:{:.5f}'.format(loss.item()))
def train_bfgs(self, niteration=50, lr=0.1):
# LBFGS optimizer
# Some optimization algorithms such as Conjugate Gradient and LBFGS need to reevaluate the function multiple times, so you have to pass in a closure that allows them to recompute your model. The closure should clear the gradients, compute the loss, and return it.
optimizer = torch.optim.LBFGS(self.parameters(), lr=lr) # lr is very important, lr>0.1 lead to failure
for i in range(niteration):
# optimizer.zero_grad()
# LBFGS
def closure():
optimizer.zero_grad()
# self.update()
loss = self.negative_log_likelihood()
loss.backward()
# print('nll:', loss.item())
# print('iter', i, ' nll:', loss.item())
print('iter', i, 'nll:{:.5f}'.format(loss.item()))
return loss
# optimizer.zero_grad()
optimizer.step(closure)
# print('loss:', loss.item())
# TODO: add conjugate gradient method
# %%
if __name__ == "__main__":
print('testing')
print(torch.__version__)
# single output test 1
xte = torch.linspace(0, 6, 100).view(-1, 1)
yte = torch.sin(xte) + 10
xtr = torch.rand(16, 1) * 6
ytr = torch.sin(xtr) + torch.randn(16, 1) * 0.5 + 10
model = cigp(xtr, ytr)
model.train_adam(200, lr=0.1)
# model.train_bfgs(50, lr=0.1)
with torch.no_grad():
ypred, ypred_var = model(xte)
plt.errorbar(xte, ypred.reshape(-1).detach(), ypred_var.sqrt().squeeze().detach(), fmt='r-.' ,alpha = 0.2)
plt.plot(xtr, ytr, 'b+')
plt.show()
# single output test 2
xte = torch.rand(128,2) * 2
yte = torch.sin(xte.sum(1)).view(-1,1) + 10
xtr = torch.rand(32, 2) * 2
ytr = torch.sin(xtr.sum(1)).view(-1,1) + torch.randn(32, 1) * 0.5 + 10
model = cigp(xtr, ytr)
model.train_adam(300, lr=0.1)
# model.train_bfgs(50, lr=0.01)
with torch.no_grad():
ypred, ypred_var = model(xte)
# plt.errorbar(xte.sum(1), ypred.reshape(-1).detach(), ystd.sqrt().squeeze().detach(), fmt='r-.' ,alpha = 0.2)
plt.plot(xte.sum(1), yte, 'b+')
plt.plot(xte.sum(1), ypred.reshape(-1).detach(), 'r+')
# plt.plot(xtr.sum(1), ytr, 'b+')
plt.show()
# multi output test
xte = torch.linspace(0, 6, 100).view(-1, 1)
yte = torch.hstack([torch.sin(xte),
torch.cos(xte),
xte.tanh()] )
xtr = torch.rand(32, 1) * 6
ytr = torch.sin(xtr) + torch.rand(32, 1) * 0.5
ytr = torch.hstack([torch.sin(xtr),
torch.cos(xtr),
xtr.tanh()] )+ torch.randn(32, 3) * 0.2
model = cigp(xtr, ytr, 1)
model.train_adam(100, lr=0.1)
# model.train_bfgs(50, lr=0.001)
with torch.no_grad():
ypred, ypred_var = model(xte)
# plt.errorbar(xte, ypred.detach(), ypred_var.sqrt().squeeze().detach(),fmt='r-.' ,alpha = 0.2)
plt.plot(xte, ypred.detach(),'r-.')
plt.plot(xtr, ytr, 'b+')
plt.plot(xte, yte, 'k-')
plt.show()
# plt.close('all')
plt.plot(xtr, ytr, 'b+')
for i in range(3):
plt.plot(xte, yte[:, i], label='truth', color='r')
plt.plot(xte, ypred[:, i], label='prediction', color='navy')
plt.fill_between(xte.squeeze(-1).detach().numpy(),
ypred[:, i].squeeze(-1).detach().numpy() + torch.sqrt(ypred_var[:, i].squeeze(-1)).detach().numpy(),
ypred[:, i].squeeze(-1).detach().numpy() - torch.sqrt(ypred_var[:, i].squeeze(-1)).detach().numpy(),
alpha=0.2)
plt.show()
# %%