kernel.py 10.7 KB
Newer Older
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
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
import numpy as np
from abc import ABC, abstractmethod

from scipy.spatial.distance import pdist, cdist, squareform

class kernel(ABC):
    def __init__(self):
        self._theta = None

    @abstractmethod
    def kernel(self):
        pass

#    @abstractmethod
#    def kernel_vector(self):
#        pass

#    @abstractmethod
#    def kernel_matrix(self):
#        pass

    @abstractmethod
    def kernel_jacobian(self):
        pass

    @abstractmethod
    def kernel_hyperparameter_gradient(self):
        pass

    @property
    def theta(self):
        return self._theta

    @theta.setter
    def theta(self, theta):
        self._theta = theta
    
    def numerical_jacobian(self,x,y, dx=1.e-5):
        if np.ndim(y) == 1:
            y = y.reshape((1,-1))
        nx = len(x)
        ny = y.shape[0]
        f0 = self.kernel(x,y)
        f_jac = np.zeros((ny,nx))
        for i in range(nx):
            x_up = np.copy(x)
            x_down = np.copy(x)
            x_up[i] += 0.5*dx
            x_down[i] -= 0.5*dx
            
            f_up = self.kernel(x_up,y)
            f_down = self.kernel(x_down,y)
            f_jac[:,i] = (f_up - f_down)/dx
        return f_jac

    def numerical_hyperparameter_gradient(self,X, dx=1.e-5):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
57
58
59
        """Calculates the numerical derivative of the kernel with respect to the
        log transformed hyperparameters.
        """
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
60
61
62
63
64
65
66
67
68
        N_data = X.shape[0]
        theta = np.copy(self.theta)
        N_hyper = len(theta)
        dK_dTheta = np.zeros((N_hyper, N_data, N_data))
        for i in range(N_hyper):
            theta_up = np.copy(theta)
            theta_down = np.copy(theta)
            theta_up[i] += 0.5*dx
            theta_down[i] -= 0.5*dx
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
69
70
71
72
73
74

            #theta_up[i] = np.log(np.exp(theta_up[i]) + 0.5*dx)
            #theta_down[i] = np.log(np.exp(theta_down[i]) - 0.5*dx)
            #dTheta = theta_up[i] - theta_down[i]
            #dTheta = np.log(np.exp(theta_up[i]) + 0.5*dx) - np.log(np.exp(theta_down[i]) - 0.5*dx)
            #print('dTheta:', dTheta)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
75
76
            
            self.theta = theta_up
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
77
            K_up = self(X, eval_gradient=False)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
78
            self.theta = theta_down
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
79
            K_down = self(X, eval_gradient=False)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
80
81
82
83
84
85
86
87
            dK_dTheta[i,:,:] = (K_up - K_down)/dx
        return dK_dTheta


class gauss_kernel(kernel):
    def __init__(self, amplitude=10.0, length_scale=10.0, amplitude_bounds=(1e0, 1e3), length_scale_bounds=(1e-1, 1e1)):
        self.amplitude = amplitude
        self.length_scale = length_scale
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
88

Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
89
90
91
        self.amplitude_bounds = amplitude_bounds
        self.length_scale_bounds = length_scale_bounds

Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
        self.theta_bounds = np.array([amplitude_bounds, length_scale_bounds])

    def __call__(self, X, eval_gradient=False):
        if np.ndim(X) == 1:
            X = X.reshape((1,-1))
        d = cdist(X / self.length_scale,
                  X / self.length_scale, metric='sqeuclidean')
        K = self.amplitude * np.exp(-0.5 * d)
        
        if eval_gradient:
            K_gradient = self.kernel_hyperparameter_gradient(X)
            return K, K_gradient
        else:
            return K
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
106
107
108
109
110
111
112
113
114
115
116
        
    def kernel(self, X,Y):
        if np.ndim(X) == 1:
            X = X.reshape((1,-1))
        if np.ndim(Y) == 1:
            Y = Y.reshape((1,-1))
        d = cdist(X / self.length_scale,
                  Y / self.length_scale, metric='sqeuclidean')
        K = self.amplitude * np.exp(-0.5 * d)
        return K

Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
117
118
119
120
    def kernel_value(self, x,y):
        K = self.kernel(x,y)
        return np.asscalar(K)
    
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
121
    def kernel_vector(self, x,Y):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
122
        K = self.kernel(x,Y).reshape(-1)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
        return K

    def kernel_matrix(self, X,Y=None):
        if Y is None:
            d = cdist(X / self.length_scale, X / self.length_scale, metric='sqeuclidean')
        else:
            d = cdist(X / self.length_scale, Y / self.length_scale, metric='sqeuclidean')
        K = self.amplitude * np.exp(-0.5 * d)
        return K

    def kernel_jacobian(self, X,Y):
        if np.ndim(X) == 1:
            X = X.reshape((1,-1))
        if np.ndim(Y) == 1:
            Y = Y.reshape((1,-1))
        K = self.kernel(X,Y).T
        dK_dd = -1./(2*self.length_scale**2)*K
        dd_df = 2*(X - Y)

        dk_df = np.multiply(dK_dd, dd_df)
        return dk_df

    @property
    def theta(self):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
147
148
149
150
151
        """Returns the log-transformed hyperparameters of the kernel.
        """
        self._theta = np.array([self.amplitude, self.length_scale])
        return np.log(self._theta)
        #return self._theta
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
152
153
154

    @theta.setter
    def theta(self, theta):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
155
156
157
158
159
160
        """Sets the hyperparameters of the kernel.

        theta: log-transformed hyperparameters
        """
        self._theta = np.exp(theta)
        #self._theta = theta
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
161
162
        self.amplitude = self._theta[0]
        self.length_scale = self._theta[1]
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
163
    
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
164
165
166
167
168
    def dK_da(self, X):
        if np.ndim(X) == 1:
            X = X.reshape((1,-1))
        d = cdist(X / self.length_scale,
                  X / self.length_scale, metric='sqeuclidean')
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
169
        dK_da = self.amplitude * np.exp(-0.5 * d)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
170
171
172
173
174
175
176
        return dK_da
        
    def dK_dl(self, X):
        if np.ndim(X) == 1:
            X = X.reshape((1,-1))
        d = cdist(X / self.length_scale,
                  X / self.length_scale, metric='sqeuclidean')
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
177
        dK_dl = self.amplitude * d * np.exp(-0.5 * d)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
178
179
180
        return dK_dl

    def kernel_hyperparameter_gradient(self, X):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
181
182
183
        """Calculates the derivative of the kernel with respect to the
        log transformed hyperparameters.
        """
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
184
185
186
187
188
189
190
191
        return np.array([self.dK_da(X), self.dK_dl(X)])
    

class double_gauss_kernel(kernel):
    def __init__(self, amplitude=10., amplitude_bounds=(1e0,1e3),
                 length_scale1=10.0, length_scale1_bounds=(1e0, 1e3),
                 length_scale2=10.0, length_scale2_bounds=(1e0, 1e3),
                 weight=0.01, weight_bounds=(0.01,0.01),
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
192
                 noise=1e-5, noise_bounds=(1e-5,1e-5)):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
193
194
195
196
        self.amplitude = amplitude
        self.length_scale1 = length_scale1
        self.length_scale2 = length_scale2
        self.weight = weight
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
197
        self.noise = noise
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
198
199
200
201
202

        self.amplitude_bounds = amplitude_bounds
        self.length_scale1_bounds = length_scale1_bounds
        self.length_scale2_bounds = length_scale2_bounds
        self.weight_bounds = weight_bounds
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
203
        self.noise_bounds = noise_bounds
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
204

Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
205
        self.theta_bounds = np.array([amplitude_bounds, length_scale1_bounds, length_scale2_bounds, weight_bounds, noise_bounds])
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
206

Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    def __call__(self, X, eval_gradient=False):
        if np.ndim(X) == 1:
            X = X.reshape((1,-1))
        d1 = cdist(X / self.length_scale1,
                  X / self.length_scale1, metric='sqeuclidean')
        d2 = cdist(X / self.length_scale2,
                  X / self.length_scale2, metric='sqeuclidean')
        K = self.amplitude * (np.exp(-0.5 * d1) + self.weight*np.exp(-0.5 * d2) + self.noise*np.eye(X.shape[0]))

        if eval_gradient:
            K_gradient = self.kernel_hyperparameter_gradient(X)
            return K, K_gradient
        else:
            return K
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
221
        
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
222
    def kernel(self, X,Y=None):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
223
224
        if np.ndim(X) == 1:
            X = X.reshape((1,-1))
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
225
226
227
        if Y is None:
            Y = X
        elif np.ndim(Y) == 1:
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
228
229
230
231
232
233
234
235
            Y = Y.reshape((1,-1))
        d1 = cdist(X / self.length_scale1,
                  Y / self.length_scale1, metric='sqeuclidean')
        d2 = cdist(X / self.length_scale2,
                  Y / self.length_scale2, metric='sqeuclidean')
        K = self.amplitude * (np.exp(-0.5 * d1) + self.weight*np.exp(-0.5 * d2))
        return K

Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
236
237
238
239
    def kernel_value(self, x,y):
        K = self.kernel(x,y)
        return np.asscalar(K)
    
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
240
    def kernel_vector(self, x,Y):
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
241
        K = self.kernel(x,Y).reshape(-1)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
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
        return K

    def kernel_matrix(self, X,Y=None):
        if Y is None:
            d = cdist(X / self.length_scale, X / self.length_scale, metric='sqeuclidean')
        else:
            d = cdist(X / self.length_scale, Y / self.length_scale, metric='sqeuclidean')
        K = np.exp(-0.5 * d)
        return K

    def kernel_jacobian(self, X,Y):
        """ Jacobian of the kernel with respect to X
        """
        if np.ndim(X) == 1:
            X = X.reshape((1,-1))
        if np.ndim(Y) == 1:
            Y = Y.reshape((1,-1))
        d1 = cdist(X / self.length_scale1,
                   Y / self.length_scale1, metric='sqeuclidean')
        d2 = cdist(X / self.length_scale2,
                   Y / self.length_scale2, metric='sqeuclidean')
        dK1_dd1 = -1/(2*self.length_scale1**2) * np.exp(-0.5 * d1)
        dK2_dd2 = -1/(2*self.length_scale2**2) * np.exp(-0.5 * d2)
        dK_dd = self.amplitude * (dK1_dd1 + self.weight*dK2_dd2)
        dd_df = 2*(X - Y)

        dk_df = np.multiply(dK_dd.T, dd_df)
        return dk_df

    @property
    def theta(self):
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
273
274
275
276
        """Returns the log-transformed hyperparameters of the kernel.
        """
        self._theta = np.array([self.amplitude, self.length_scale1, self.length_scale2, self.weight, self.noise])
        return np.log(self._theta)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
277
278
279

    @theta.setter
    def theta(self, theta):
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
280
281
282
283
284
        """Sets the hyperparameters of the kernel.

        theta: log-transformed hyperparameters
        """
        self._theta = np.exp(theta)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
285
286
287
288
        self.amplitude = self._theta[0]
        self.length_scale1 = self._theta[1]
        self.length_scale2 = self._theta[2]
        self.weight = self._theta[3]
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
289
        self.noise = self._theta[4]
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
290
291
292
293
294
295

    def dK_da(self, X):
        d1 = cdist(X / self.length_scale1,
                   X / self.length_scale1, metric='sqeuclidean')
        d2 = cdist(X / self.length_scale2,
                   X / self.length_scale2, metric='sqeuclidean')
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
296
        dK_da = self.amplitude * (np.exp(-0.5 * d1) + self.weight*np.exp(-0.5 * d2) + self.noise*np.eye(X.shape[0]))
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
297
298
299
300
301
        return dK_da
        
    def dK_dl1(self, X):
        d1 = cdist(X / self.length_scale1,
                   X / self.length_scale1, metric='sqeuclidean')
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
302
        dK_dl1 = self.amplitude*d1 * np.exp(-0.5 * d1)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
303
304
305
306
307
        return dK_dl1

    def dK_dl2(self, X):
        d2 = cdist(X / self.length_scale2,
                   X / self.length_scale2, metric='sqeuclidean')
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
308
        dK_dl2 = self.amplitude*self.weight*d2 * np.exp(-0.5 * d2)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
309
310
311
312
313
        return dK_dl2

    def dK_dw(self, X):
        d2 = cdist(X / self.length_scale2,
                   X / self.length_scale2, metric='sqeuclidean')
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
314
        dK_dl2 = self.amplitude*self.weight*np.exp(-0.5 * d2)
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
315
316
        return dK_dl2

Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
317
    def dK_dn(self, X):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
318
        dK_dn = self.amplitude * self.noise * np.eye(X.shape[0])
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
319
320
        return dK_dn

Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
321
    def kernel_hyperparameter_gradient(self, X):
Malthe Kjær Bisbo's avatar
Malthe Kjær Bisbo committed
322
323
324
        """Calculates the derivative of the kernel with respect to the
        log transformed hyperparameters.
        """
Malthe Kjær Bisbo's avatar
update    
Malthe Kjær Bisbo committed
325
        return np.array([self.dK_da(X), self.dK_dl1(X), self.dK_dl2(X), self.dK_dw(X), self.dK_dn(X)])