Refactoring: self.D > self.input_dim in kernels

This commit is contained in:
Max Zwiessele 2013-06-05 15:21:57 +01:00
parent b535cf2e30
commit 35c2a8b521
12 changed files with 232 additions and 232 deletions

View file

@ -14,10 +14,10 @@ class Matern32(kernpart):
.. math:: .. math::
k(r) = \\sigma^2 (1 + \\sqrt{3} r) \exp(- \sqrt{3} r) \\ \\ \\ \\ \\text{ where } r = \sqrt{\sum_{i=1}^D \\frac{(x_i-y_i)^2}{\ell_i^2} } k(r) = \\sigma^2 (1 + \\sqrt{3} r) \exp(- \sqrt{3} r) \\ \\ \\ \\ \\text{ where } r = \sqrt{\sum_{i=1}^input_dim \\frac{(x_i-y_i)^2}{\ell_i^2} }
:param D: the number of input dimensions :param input_dim: the number of input dimensions
:type D: int :type input_dim: int
:param variance: the variance :math:`\sigma^2` :param variance: the variance :math:`\sigma^2`
:type variance: float :type variance: float
:param lengthscale: the vector of lengthscale :math:`\ell_i` :param lengthscale: the vector of lengthscale :math:`\ell_i`
@ -28,8 +28,8 @@ class Matern32(kernpart):
""" """
def __init__(self,D,variance=1.,lengthscale=None,ARD=False): def __init__(self,input_dim,variance=1.,lengthscale=None,ARD=False):
self.D = D self.input_dim = input_dim
self.ARD = ARD self.ARD = ARD
if ARD == False: if ARD == False:
self.Nparam = 2 self.Nparam = 2
@ -40,13 +40,13 @@ class Matern32(kernpart):
else: else:
lengthscale = np.ones(1) lengthscale = np.ones(1)
else: else:
self.Nparam = self.D + 1 self.Nparam = self.input_dim + 1
self.name = 'Mat32' self.name = 'Mat32'
if lengthscale is not None: if lengthscale is not None:
lengthscale = np.asarray(lengthscale) lengthscale = np.asarray(lengthscale)
assert lengthscale.size == self.D, "bad number of lengthscales" assert lengthscale.size == self.input_dim, "bad number of lengthscales"
else: else:
lengthscale = np.ones(self.D) lengthscale = np.ones(self.input_dim)
self._set_params(np.hstack((variance,lengthscale.flatten()))) self._set_params(np.hstack((variance,lengthscale.flatten())))
def _get_params(self): def _get_params(self):
@ -111,7 +111,7 @@ class Matern32(kernpart):
def Gram_matrix(self,F,F1,F2,lower,upper): def Gram_matrix(self,F,F1,F2,lower,upper):
""" """
Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to D=1. Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to input_dim=1.
:param F: vector of functions :param F: vector of functions
:type F: np.array :type F: np.array
@ -122,7 +122,7 @@ class Matern32(kernpart):
:param lower,upper: boundaries of the input domain :param lower,upper: boundaries of the input domain
:type lower,upper: floats :type lower,upper: floats
""" """
assert self.D == 1 assert self.input_dim == 1
def L(x,i): def L(x,i):
return(3./self.lengthscale**2*F[i](x) + 2*np.sqrt(3)/self.lengthscale*F1[i](x) + F2[i](x)) return(3./self.lengthscale**2*F[i](x) + 2*np.sqrt(3)/self.lengthscale*F1[i](x) + F2[i](x))
n = F.shape[0] n = F.shape[0]

View file

@ -13,10 +13,10 @@ class Matern52(kernpart):
.. math:: .. math::
k(r) = \sigma^2 (1 + \sqrt{5} r + \\frac53 r^2) \exp(- \sqrt{5} r) \ \ \ \ \ \\text{ where } r = \sqrt{\sum_{i=1}^D \\frac{(x_i-y_i)^2}{\ell_i^2} } k(r) = \sigma^2 (1 + \sqrt{5} r + \\frac53 r^2) \exp(- \sqrt{5} r) \ \ \ \ \ \\text{ where } r = \sqrt{\sum_{i=1}^input_dim \\frac{(x_i-y_i)^2}{\ell_i^2} }
:param D: the number of input dimensions :param input_dim: the number of input dimensions
:type D: int :type input_dim: int
:param variance: the variance :math:`\sigma^2` :param variance: the variance :math:`\sigma^2`
:type variance: float :type variance: float
:param lengthscale: the vector of lengthscale :math:`\ell_i` :param lengthscale: the vector of lengthscale :math:`\ell_i`
@ -26,8 +26,8 @@ class Matern52(kernpart):
:rtype: kernel object :rtype: kernel object
""" """
def __init__(self,D,variance=1.,lengthscale=None,ARD=False): def __init__(self,input_dim,variance=1.,lengthscale=None,ARD=False):
self.D = D self.input_dim = input_dim
self.ARD = ARD self.ARD = ARD
if ARD == False: if ARD == False:
self.Nparam = 2 self.Nparam = 2
@ -38,13 +38,13 @@ class Matern52(kernpart):
else: else:
lengthscale = np.ones(1) lengthscale = np.ones(1)
else: else:
self.Nparam = self.D + 1 self.Nparam = self.input_dim + 1
self.name = 'Mat52' self.name = 'Mat52'
if lengthscale is not None: if lengthscale is not None:
lengthscale = np.asarray(lengthscale) lengthscale = np.asarray(lengthscale)
assert lengthscale.size == self.D, "bad number of lengthscales" assert lengthscale.size == self.input_dim, "bad number of lengthscales"
else: else:
lengthscale = np.ones(self.D) lengthscale = np.ones(self.input_dim)
self._set_params(np.hstack((variance,lengthscale.flatten()))) self._set_params(np.hstack((variance,lengthscale.flatten())))
def _get_params(self): def _get_params(self):
@ -109,7 +109,7 @@ class Matern52(kernpart):
def Gram_matrix(self,F,F1,F2,F3,lower,upper): def Gram_matrix(self,F,F1,F2,F3,lower,upper):
""" """
Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to D=1. Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to input_dim=1.
:param F: vector of functions :param F: vector of functions
:type F: np.array :type F: np.array
@ -122,7 +122,7 @@ class Matern52(kernpart):
:param lower,upper: boundaries of the input domain :param lower,upper: boundaries of the input domain
:type lower,upper: floats :type lower,upper: floats
""" """
assert self.D == 1 assert self.input_dim == 1
def L(x,i): def L(x,i):
return(5*np.sqrt(5)/self.lengthscale**3*F[i](x) + 15./self.lengthscale**2*F1[i](x)+ 3*np.sqrt(5)/self.lengthscale*F2[i](x) + F3[i](x)) return(5*np.sqrt(5)/self.lengthscale**3*F[i](x) + 15./self.lengthscale**2*F1[i](x)+ 3*np.sqrt(5)/self.lengthscale*F2[i](x) + F3[i](x))
n = F.shape[0] n = F.shape[0]

View file

@ -9,14 +9,14 @@ from GPy.util.decorators import silence_errors
class periodic_Matern32(kernpart): class periodic_Matern32(kernpart):
""" """
Kernel of the periodic subspace (up to a given frequency) of a Matern 3/2 RKHS. Only defined for D=1. Kernel of the periodic subspace (up to a given frequency) of a Matern 3/2 RKHS. Only defined for input_dim=1.
:param D: the number of input dimensions :param input_dim: the number of input dimensions
:type D: int :type input_dim: int
:param variance: the variance of the Matern kernel :param variance: the variance of the Matern kernel
:type variance: float :type variance: float
:param lengthscale: the lengthscale of the Matern kernel :param lengthscale: the lengthscale of the Matern kernel
:type lengthscale: np.ndarray of size (D,) :type lengthscale: np.ndarray of size (input_dim,)
:param period: the period :param period: the period
:type period: float :type period: float
:param n_freq: the number of frequencies considered for the periodic subspace :param n_freq: the number of frequencies considered for the periodic subspace
@ -25,10 +25,10 @@ class periodic_Matern32(kernpart):
""" """
def __init__(self,D=1,variance=1.,lengthscale=None,period=2*np.pi,n_freq=10,lower=0.,upper=4*np.pi): def __init__(self,input_dim=1,variance=1.,lengthscale=None,period=2*np.pi,n_freq=10,lower=0.,upper=4*np.pi):
assert D==1, "Periodic kernels are only defined for D=1" assert input_dim==1, "Periodic kernels are only defined for input_dim=1"
self.name = 'periodic_Mat32' self.name = 'periodic_Mat32'
self.D = D self.input_dim = input_dim
if lengthscale is not None: if lengthscale is not None:
lengthscale = np.asarray(lengthscale) lengthscale = np.asarray(lengthscale)
assert lengthscale.size == 1, "Wrong size: only one lengthscale needed" assert lengthscale.size == 1, "Wrong size: only one lengthscale needed"

View file

@ -9,14 +9,14 @@ from GPy.util.decorators import silence_errors
class periodic_Matern52(kernpart): class periodic_Matern52(kernpart):
""" """
Kernel of the periodic subspace (up to a given frequency) of a Matern 5/2 RKHS. Only defined for D=1. Kernel of the periodic subspace (up to a given frequency) of a Matern 5/2 RKHS. Only defined for input_dim=1.
:param D: the number of input dimensions :param input_dim: the number of input dimensions
:type D: int :type input_dim: int
:param variance: the variance of the Matern kernel :param variance: the variance of the Matern kernel
:type variance: float :type variance: float
:param lengthscale: the lengthscale of the Matern kernel :param lengthscale: the lengthscale of the Matern kernel
:type lengthscale: np.ndarray of size (D,) :type lengthscale: np.ndarray of size (input_dim,)
:param period: the period :param period: the period
:type period: float :type period: float
:param n_freq: the number of frequencies considered for the periodic subspace :param n_freq: the number of frequencies considered for the periodic subspace
@ -25,10 +25,10 @@ class periodic_Matern52(kernpart):
""" """
def __init__(self,D=1,variance=1.,lengthscale=None,period=2*np.pi,n_freq=10,lower=0.,upper=4*np.pi): def __init__(self,input_dim=1,variance=1.,lengthscale=None,period=2*np.pi,n_freq=10,lower=0.,upper=4*np.pi):
assert D==1, "Periodic kernels are only defined for D=1" assert input_dim==1, "Periodic kernels are only defined for input_dim=1"
self.name = 'periodic_Mat52' self.name = 'periodic_Mat52'
self.D = D self.input_dim = input_dim
if lengthscale is not None: if lengthscale is not None:
lengthscale = np.asarray(lengthscale) lengthscale = np.asarray(lengthscale)
assert lengthscale.size == 1, "Wrong size: only one lengthscale needed" assert lengthscale.size == 1, "Wrong size: only one lengthscale needed"

View file

@ -9,14 +9,14 @@ from GPy.util.decorators import silence_errors
class periodic_exponential(kernpart): class periodic_exponential(kernpart):
""" """
Kernel of the periodic subspace (up to a given frequency) of a exponential (Matern 1/2) RKHS. Only defined for D=1. Kernel of the periodic subspace (up to a given frequency) of a exponential (Matern 1/2) RKHS. Only defined for input_dim=1.
:param D: the number of input dimensions :param input_dim: the number of input dimensions
:type D: int :type input_dim: int
:param variance: the variance of the Matern kernel :param variance: the variance of the Matern kernel
:type variance: float :type variance: float
:param lengthscale: the lengthscale of the Matern kernel :param lengthscale: the lengthscale of the Matern kernel
:type lengthscale: np.ndarray of size (D,) :type lengthscale: np.ndarray of size (input_dim,)
:param period: the period :param period: the period
:type period: float :type period: float
:param n_freq: the number of frequencies considered for the periodic subspace :param n_freq: the number of frequencies considered for the periodic subspace
@ -25,10 +25,10 @@ class periodic_exponential(kernpart):
""" """
def __init__(self,D=1,variance=1.,lengthscale=None,period=2*np.pi,n_freq=10,lower=0.,upper=4*np.pi): def __init__(self,input_dim=1,variance=1.,lengthscale=None,period=2*np.pi,n_freq=10,lower=0.,upper=4*np.pi):
assert D==1, "Periodic kernels are only defined for D=1" assert input_dim==1, "Periodic kernels are only defined for input_dim=1"
self.name = 'periodic_exp' self.name = 'periodic_exp'
self.D = D self.input_dim = input_dim
if lengthscale is not None: if lengthscale is not None:
lengthscale = np.asarray(lengthscale) lengthscale = np.asarray(lengthscale)
assert lengthscale.size == 1, "Wrong size: only one lengthscale needed" assert lengthscale.size == 1, "Wrong size: only one lengthscale needed"

View file

@ -16,7 +16,7 @@ class prod_orthogonal(kernpart):
""" """
def __init__(self,k1,k2): def __init__(self,k1,k2):
self.D = k1.D + k2.D self.input_dim = k1.input_dim + k2.input_dim
self.Nparam = k1.Nparam + k2.Nparam self.Nparam = k1.Nparam + k2.Nparam
self.name = k1.name + '<times>' + k2.name self.name = k1.name + '<times>' + k2.name
self.k1 = k1 self.k1 = k1
@ -45,42 +45,42 @@ class prod_orthogonal(kernpart):
"""derivative of the covariance matrix with respect to the parameters.""" """derivative of the covariance matrix with respect to the parameters."""
self._K_computations(X,X2) self._K_computations(X,X2)
if X2 is None: if X2 is None:
self.k1.dK_dtheta(dL_dK*self._K2, X[:,:self.k1.D], None, target[:self.k1.Nparam]) self.k1.dK_dtheta(dL_dK*self._K2, X[:,:self.k1.input_dim], None, target[:self.k1.Nparam])
self.k2.dK_dtheta(dL_dK*self._K1, X[:,self.k1.D:], None, target[self.k1.Nparam:]) self.k2.dK_dtheta(dL_dK*self._K1, X[:,self.k1.input_dim:], None, target[self.k1.Nparam:])
else: else:
self.k1.dK_dtheta(dL_dK*self._K2, X[:,:self.k1.D], X2[:,:self.k1.D], target[:self.k1.Nparam]) self.k1.dK_dtheta(dL_dK*self._K2, X[:,:self.k1.input_dim], X2[:,:self.k1.input_dim], target[:self.k1.Nparam])
self.k2.dK_dtheta(dL_dK*self._K1, X[:,self.k1.D:], X2[:,self.k1.D:], target[self.k1.Nparam:]) self.k2.dK_dtheta(dL_dK*self._K1, X[:,self.k1.input_dim:], X2[:,self.k1.input_dim:], target[self.k1.Nparam:])
def Kdiag(self,X,target): def Kdiag(self,X,target):
"""Compute the diagonal of the covariance matrix associated to X.""" """Compute the diagonal of the covariance matrix associated to X."""
target1 = np.zeros(X.shape[0]) target1 = np.zeros(X.shape[0])
target2 = np.zeros(X.shape[0]) target2 = np.zeros(X.shape[0])
self.k1.Kdiag(X[:,:self.k1.D],target1) self.k1.Kdiag(X[:,:self.k1.input_dim],target1)
self.k2.Kdiag(X[:,self.k1.D:],target2) self.k2.Kdiag(X[:,self.k1.input_dim:],target2)
target += target1 * target2 target += target1 * target2
def dKdiag_dtheta(self,dL_dKdiag,X,target): def dKdiag_dtheta(self,dL_dKdiag,X,target):
K1 = np.zeros(X.shape[0]) K1 = np.zeros(X.shape[0])
K2 = np.zeros(X.shape[0]) K2 = np.zeros(X.shape[0])
self.k1.Kdiag(X[:,:self.k1.D],K1) self.k1.Kdiag(X[:,:self.k1.input_dim],K1)
self.k2.Kdiag(X[:,self.k1.D:],K2) self.k2.Kdiag(X[:,self.k1.input_dim:],K2)
self.k1.dKdiag_dtheta(dL_dKdiag*K2,X[:,:self.k1.D],target[:self.k1.Nparam]) self.k1.dKdiag_dtheta(dL_dKdiag*K2,X[:,:self.k1.input_dim],target[:self.k1.Nparam])
self.k2.dKdiag_dtheta(dL_dKdiag*K1,X[:,self.k1.D:],target[self.k1.Nparam:]) self.k2.dKdiag_dtheta(dL_dKdiag*K1,X[:,self.k1.input_dim:],target[self.k1.Nparam:])
def dK_dX(self,dL_dK,X,X2,target): def dK_dX(self,dL_dK,X,X2,target):
"""derivative of the covariance matrix with respect to X.""" """derivative of the covariance matrix with respect to X."""
self._K_computations(X,X2) self._K_computations(X,X2)
self.k1.dK_dX(dL_dK*self._K2, X[:,:self.k1.D], X2[:,:self.k1.D], target) self.k1.dK_dX(dL_dK*self._K2, X[:,:self.k1.input_dim], X2[:,:self.k1.input_dim], target)
self.k2.dK_dX(dL_dK*self._K1, X[:,self.k1.D:], X2[:,self.k1.D:], target) self.k2.dK_dX(dL_dK*self._K1, X[:,self.k1.input_dim:], X2[:,self.k1.input_dim:], target)
def dKdiag_dX(self, dL_dKdiag, X, target): def dKdiag_dX(self, dL_dKdiag, X, target):
K1 = np.zeros(X.shape[0]) K1 = np.zeros(X.shape[0])
K2 = np.zeros(X.shape[0]) K2 = np.zeros(X.shape[0])
self.k1.Kdiag(X[:,0:self.k1.D],K1) self.k1.Kdiag(X[:,0:self.k1.input_dim],K1)
self.k2.Kdiag(X[:,self.k1.D:],K2) self.k2.Kdiag(X[:,self.k1.input_dim:],K2)
self.k1.dK_dX(dL_dKdiag*K2, X[:,:self.k1.D], target) self.k1.dK_dX(dL_dKdiag*K2, X[:,:self.k1.input_dim], target)
self.k2.dK_dX(dL_dKdiag*K1, X[:,self.k1.D:], target) self.k2.dK_dX(dL_dKdiag*K1, X[:,self.k1.input_dim:], target)
def _K_computations(self,X,X2): def _K_computations(self,X,X2):
if not (np.array_equal(X,self._X) and np.array_equal(X2,self._X2) and np.array_equal(self._params , self._get_params())): if not (np.array_equal(X,self._X) and np.array_equal(X2,self._X2) and np.array_equal(self._params , self._get_params())):
@ -90,12 +90,12 @@ class prod_orthogonal(kernpart):
self._X2 = None self._X2 = None
self._K1 = np.zeros((X.shape[0],X.shape[0])) self._K1 = np.zeros((X.shape[0],X.shape[0]))
self._K2 = np.zeros((X.shape[0],X.shape[0])) self._K2 = np.zeros((X.shape[0],X.shape[0]))
self.k1.K(X[:,:self.k1.D],None,self._K1) self.k1.K(X[:,:self.k1.input_dim],None,self._K1)
self.k2.K(X[:,self.k1.D:],None,self._K2) self.k2.K(X[:,self.k1.input_dim:],None,self._K2)
else: else:
self._X2 = X2.copy() self._X2 = X2.copy()
self._K1 = np.zeros((X.shape[0],X2.shape[0])) self._K1 = np.zeros((X.shape[0],X2.shape[0]))
self._K2 = np.zeros((X.shape[0],X2.shape[0])) self._K2 = np.zeros((X.shape[0],X2.shape[0]))
self.k1.K(X[:,:self.k1.D],X2[:,:self.k1.D],self._K1) self.k1.K(X[:,:self.k1.input_dim],X2[:,:self.k1.input_dim],self._K1)
self.k2.K(X[:,self.k1.D:],X2[:,self.k1.D:],self._K2) self.k2.K(X[:,self.k1.input_dim:],X2[:,self.k1.input_dim:],self._K2)

View file

@ -13,8 +13,8 @@ class rational_quadratic(kernpart):
k(r) = \sigma^2 \\bigg( 1 + \\frac{r^2}{2 \ell^2} \\bigg)^{- \\alpha} \ \ \ \ \ \\text{ where } r^2 = (x-y)^2 k(r) = \sigma^2 \\bigg( 1 + \\frac{r^2}{2 \ell^2} \\bigg)^{- \\alpha} \ \ \ \ \ \\text{ where } r^2 = (x-y)^2
:param D: the number of input dimensions :param input_dim: the number of input dimensions
:type D: int (D=1 is the only value currently supported) :type input_dim: int (input_dim=1 is the only value currently supported)
:param variance: the variance :math:`\sigma^2` :param variance: the variance :math:`\sigma^2`
:type variance: float :type variance: float
:param lengthscale: the lengthscale :math:`\ell` :param lengthscale: the lengthscale :math:`\ell`
@ -24,9 +24,9 @@ class rational_quadratic(kernpart):
:rtype: kernpart object :rtype: kernpart object
""" """
def __init__(self,D,variance=1.,lengthscale=1.,power=1.): def __init__(self,input_dim,variance=1.,lengthscale=1.,power=1.):
assert D == 1, "For this kernel we assume D=1" assert input_dim == 1, "For this kernel we assume input_dim=1"
self.D = D self.input_dim = input_dim
self.Nparam = 3 self.Nparam = 3
self.name = 'rat_quad' self.name = 'rat_quad'
self.variance = variance self.variance = variance

View file

@ -31,7 +31,7 @@ class rbf(kernpart):
.. Note: this object implements both the ARD and 'spherical' version of the function .. Note: this object implements both the ARD and 'spherical' version of the function
""" """
def __init__(self,input_dim,variance=1.,lengthscale=None,ARD=False): def __init__(self, input_dim, variance=1., lengthscale=None, ARD=False):
self.input_dim = input_dim self.input_dim = input_dim
self.name = 'rbf' self.name = 'rbf'
self.ARD = ARD self.ARD = ARD
@ -50,52 +50,52 @@ class rbf(kernpart):
else: else:
lengthscale = np.ones(self.input_dim) lengthscale = np.ones(self.input_dim)
self._set_params(np.hstack((variance,lengthscale.flatten()))) self._set_params(np.hstack((variance, lengthscale.flatten())))
#initialize cache # initialize cache
self._Z, self._mu, self._S = np.empty(shape=(3,1)) self._Z, self._mu, self._S = np.empty(shape=(3, 1))
self._X, self._X2, self._params = np.empty(shape=(3,1)) self._X, self._X2, self._params = np.empty(shape=(3, 1))
#a set of optional args to pass to weave # a set of optional args to pass to weave
self.weave_options = {'headers' : ['<omp.h>'], self.weave_options = {'headers' : ['<omp.h>'],
'extra_compile_args': ['-fopenmp -O3'], #-march=native'], 'extra_compile_args': ['-fopenmp -O3'], # -march=native'],
'extra_link_args' : ['-lgomp']} 'extra_link_args' : ['-lgomp']}
def _get_params(self): def _get_params(self):
return np.hstack((self.variance,self.lengthscale)) return np.hstack((self.variance, self.lengthscale))
def _set_params(self,x): def _set_params(self, x):
assert x.size==(self.Nparam) assert x.size == (self.Nparam)
self.variance = x[0] self.variance = x[0]
self.lengthscale = x[1:] self.lengthscale = x[1:]
self.lengthscale2 = np.square(self.lengthscale) self.lengthscale2 = np.square(self.lengthscale)
#reset cached results # reset cached results
self._X, self._X2, self._params = np.empty(shape=(3,1)) self._X, self._X2, self._params = np.empty(shape=(3, 1))
self._Z, self._mu, self._S = np.empty(shape=(3,1)) # cached versions of Z,mu,S self._Z, self._mu, self._S = np.empty(shape=(3, 1)) # cached versions of Z,mu,S
def _get_param_names(self): def _get_param_names(self):
if self.Nparam == 2: if self.Nparam == 2:
return ['variance','lengthscale'] return ['variance', 'lengthscale']
else: else:
return ['variance']+['lengthscale_%i'%i for i in range(self.lengthscale.size)] return ['variance'] + ['lengthscale_%i' % i for i in range(self.lengthscale.size)]
def K(self,X,X2,target): def K(self, X, X2, target):
self._K_computations(X,X2) self._K_computations(X, X2)
target += self.variance*self._K_dvar target += self.variance * self._K_dvar
def Kdiag(self,X,target): def Kdiag(self, X, target):
np.add(target,self.variance,target) np.add(target, self.variance, target)
def dK_dtheta(self,dL_dK,X,X2,target): def dK_dtheta(self, dL_dK, X, X2, target):
self._K_computations(X,X2) self._K_computations(X, X2)
target[0] += np.sum(self._K_dvar*dL_dK) target[0] += np.sum(self._K_dvar * dL_dK)
if self.ARD: if self.ARD:
dvardLdK = self._K_dvar*dL_dK dvardLdK = self._K_dvar * dL_dK
var_len3 = self.variance/np.power(self.lengthscale,3) var_len3 = self.variance / np.power(self.lengthscale, 3)
if X2 is None: if X2 is None:
#save computation for the symmetrical case # save computation for the symmetrical case
dvardLdK += dvardLdK.T dvardLdK += dvardLdK.T
code = """ code = """
int q,i,j; int q,i,j;
@ -126,23 +126,23 @@ class rbf(kernpart):
} }
""" """
N, M, input_dim = X.shape[0], X2.shape[0], self.input_dim N, M, input_dim = X.shape[0], X2.shape[0], self.input_dim
#[np.add(target[1+q:2+q],var_len3[q]*np.sum(dvardLdK*np.square(X[:,q][:,None]-X2[:,q][None,:])),target[1+q:2+q]) for q in range(self.input_dim)] # [np.add(target[1+q:2+q],var_len3[q]*np.sum(dvardLdK*np.square(X[:,q][:,None]-X2[:,q][None,:])),target[1+q:2+q]) for q in range(self.input_dim)]
weave.inline(code, arg_names=['N','M','input_dim','X','X2','target','dvardLdK','var_len3'], weave.inline(code, arg_names=['N', 'M', 'input_dim', 'X', 'X2', 'target', 'dvardLdK', 'var_len3'],
type_converters=weave.converters.blitz,**self.weave_options) type_converters=weave.converters.blitz, **self.weave_options)
else: else:
target[1] += (self.variance/self.lengthscale)*np.sum(self._K_dvar*self._K_dist2*dL_dK) target[1] += (self.variance / self.lengthscale) * np.sum(self._K_dvar * self._K_dist2 * dL_dK)
def dKdiag_dtheta(self,dL_dKdiag,X,target): def dKdiag_dtheta(self, dL_dKdiag, X, target):
#NB: derivative of diagonal elements wrt lengthscale is 0 # NB: derivative of diagonal elements wrt lengthscale is 0
target[0] += np.sum(dL_dKdiag) target[0] += np.sum(dL_dKdiag)
def dK_dX(self,dL_dK,X,X2,target): def dK_dX(self, dL_dK, X, X2, target):
self._K_computations(X,X2) self._K_computations(X, X2)
_K_dist = X[:,None,:]-X2[None,:,:] #don't cache this in _K_computations because it is high memory. If this function is being called, chances are we're not in the high memory arena. _K_dist = X[:, None, :] - X2[None, :, :] # don't cache this in _K_computations because it is high memory. If this function is being called, chances are we're not in the high memory arena.
dK_dX = (-self.variance/self.lengthscale2)*np.transpose(self._K_dvar[:,:,np.newaxis]*_K_dist,(1,0,2)) dK_dX = (-self.variance / self.lengthscale2) * np.transpose(self._K_dvar[:, :, np.newaxis] * _K_dist, (1, 0, 2))
target += np.sum(dK_dX*dL_dK.T[:,:,None],0) target += np.sum(dK_dX * dL_dK.T[:, :, None], 0)
def dKdiag_dX(self,dL_dKdiag,X,target): def dKdiag_dX(self, dL_dKdiag, X, target):
pass pass
@ -150,141 +150,141 @@ class rbf(kernpart):
# PSI statistics # # PSI statistics #
#---------------------------------------# #---------------------------------------#
def psi0(self,Z,mu,S,target): def psi0(self, Z, mu, S, target):
target += self.variance target += self.variance
def dpsi0_dtheta(self,dL_dpsi0,Z,mu,S,target): def dpsi0_dtheta(self, dL_dpsi0, Z, mu, S, target):
target[0] += np.sum(dL_dpsi0) target[0] += np.sum(dL_dpsi0)
def dpsi0_dmuS(self,dL_dpsi0,Z,mu,S,target_mu,target_S): def dpsi0_dmuS(self, dL_dpsi0, Z, mu, S, target_mu, target_S):
pass pass
def psi1(self,Z,mu,S,target): def psi1(self, Z, mu, S, target):
self._psi_computations(Z,mu,S) self._psi_computations(Z, mu, S)
target += self._psi1 target += self._psi1
def dpsi1_dtheta(self,dL_dpsi1,Z,mu,S,target): def dpsi1_dtheta(self, dL_dpsi1, Z, mu, S, target):
self._psi_computations(Z,mu,S) self._psi_computations(Z, mu, S)
denom_deriv = S[:,None,:]/(self.lengthscale**3+self.lengthscale*S[:,None,:]) denom_deriv = S[:, None, :] / (self.lengthscale ** 3 + self.lengthscale * S[:, None, :])
d_length = self._psi1[:,:,None]*(self.lengthscale*np.square(self._psi1_dist/(self.lengthscale2+S[:,None,:])) + denom_deriv) d_length = self._psi1[:, :, None] * (self.lengthscale * np.square(self._psi1_dist / (self.lengthscale2 + S[:, None, :])) + denom_deriv)
target[0] += np.sum(dL_dpsi1*self._psi1/self.variance) target[0] += np.sum(dL_dpsi1 * self._psi1 / self.variance)
dpsi1_dlength = d_length*dL_dpsi1[:,:,None] dpsi1_dlength = d_length * dL_dpsi1[:, :, None]
if not self.ARD: if not self.ARD:
target[1] += dpsi1_dlength.sum() target[1] += dpsi1_dlength.sum()
else: else:
target[1:] += dpsi1_dlength.sum(0).sum(0) target[1:] += dpsi1_dlength.sum(0).sum(0)
def dpsi1_dZ(self,dL_dpsi1,Z,mu,S,target): def dpsi1_dZ(self, dL_dpsi1, Z, mu, S, target):
self._psi_computations(Z,mu,S) self._psi_computations(Z, mu, S)
denominator = (self.lengthscale2*(self._psi1_denom)) denominator = (self.lengthscale2 * (self._psi1_denom))
dpsi1_dZ = - self._psi1[:,:,None] * ((self._psi1_dist/denominator)) dpsi1_dZ = -self._psi1[:, :, None] * ((self._psi1_dist / denominator))
target += np.sum(dL_dpsi1.T[:,:,None] * dpsi1_dZ, 0) target += np.sum(dL_dpsi1.T[:, :, None] * dpsi1_dZ, 0)
def dpsi1_dmuS(self,dL_dpsi1,Z,mu,S,target_mu,target_S): def dpsi1_dmuS(self, dL_dpsi1, Z, mu, S, target_mu, target_S):
self._psi_computations(Z,mu,S) self._psi_computations(Z, mu, S)
tmp = self._psi1[:,:,None]/self.lengthscale2/self._psi1_denom tmp = self._psi1[:, :, None] / self.lengthscale2 / self._psi1_denom
target_mu += np.sum(dL_dpsi1.T[:, :, None]*tmp*self._psi1_dist,1) target_mu += np.sum(dL_dpsi1.T[:, :, None] * tmp * self._psi1_dist, 1)
target_S += np.sum(dL_dpsi1.T[:, :, None]*0.5*tmp*(self._psi1_dist_sq-1),1) target_S += np.sum(dL_dpsi1.T[:, :, None] * 0.5 * tmp * (self._psi1_dist_sq - 1), 1)
def psi2(self,Z,mu,S,target): def psi2(self, Z, mu, S, target):
self._psi_computations(Z,mu,S) self._psi_computations(Z, mu, S)
target += self._psi2 target += self._psi2
def dpsi2_dtheta(self,dL_dpsi2,Z,mu,S,target): def dpsi2_dtheta(self, dL_dpsi2, Z, mu, S, target):
"""Shape N,M,M,Ntheta""" """Shape N,M,M,Ntheta"""
self._psi_computations(Z,mu,S) self._psi_computations(Z, mu, S)
d_var = 2.*self._psi2/self.variance d_var = 2.*self._psi2 / self.variance
d_length = 2.*self._psi2[:,:,:,None]*(self._psi2_Zdist_sq*self._psi2_denom + self._psi2_mudist_sq + S[:,None,None,:]/self.lengthscale2)/(self.lengthscale*self._psi2_denom) d_length = 2.*self._psi2[:, :, :, None] * (self._psi2_Zdist_sq * self._psi2_denom + self._psi2_mudist_sq + S[:, None, None, :] / self.lengthscale2) / (self.lengthscale * self._psi2_denom)
target[0] += np.sum(dL_dpsi2*d_var) target[0] += np.sum(dL_dpsi2 * d_var)
dpsi2_dlength = d_length*dL_dpsi2[:,:,:,None] dpsi2_dlength = d_length * dL_dpsi2[:, :, :, None]
if not self.ARD: if not self.ARD:
target[1] += dpsi2_dlength.sum() target[1] += dpsi2_dlength.sum()
else: else:
target[1:] += dpsi2_dlength.sum(0).sum(0).sum(0) target[1:] += dpsi2_dlength.sum(0).sum(0).sum(0)
def dpsi2_dZ(self,dL_dpsi2,Z,mu,S,target): def dpsi2_dZ(self, dL_dpsi2, Z, mu, S, target):
self._psi_computations(Z,mu,S) self._psi_computations(Z, mu, S)
term1 = self._psi2_Zdist/self.lengthscale2 # M, M, input_dim term1 = self._psi2_Zdist / self.lengthscale2 # M, M, input_dim
term2 = self._psi2_mudist/self._psi2_denom/self.lengthscale2 # N, M, M, input_dim term2 = self._psi2_mudist / self._psi2_denom / self.lengthscale2 # N, M, M, input_dim
dZ = self._psi2[:,:,:,None] * (term1[None] + term2) dZ = self._psi2[:, :, :, None] * (term1[None] + term2)
target += (dL_dpsi2[:,:,:,None]*dZ).sum(0).sum(0) target += (dL_dpsi2[:, :, :, None] * dZ).sum(0).sum(0)
def dpsi2_dmuS(self,dL_dpsi2,Z,mu,S,target_mu,target_S): def dpsi2_dmuS(self, dL_dpsi2, Z, mu, S, target_mu, target_S):
"""Think N,M,M,input_dim """ """Think N,M,M,input_dim """
self._psi_computations(Z,mu,S) self._psi_computations(Z, mu, S)
tmp = self._psi2[:,:,:,None]/self.lengthscale2/self._psi2_denom tmp = self._psi2[:, :, :, None] / self.lengthscale2 / self._psi2_denom
target_mu += -2.*(dL_dpsi2[:,:,:,None]*tmp*self._psi2_mudist).sum(1).sum(1) target_mu += -2.*(dL_dpsi2[:, :, :, None] * tmp * self._psi2_mudist).sum(1).sum(1)
target_S += (dL_dpsi2[:,:,:,None]*tmp*(2.*self._psi2_mudist_sq-1)).sum(1).sum(1) target_S += (dL_dpsi2[:, :, :, None] * tmp * (2.*self._psi2_mudist_sq - 1)).sum(1).sum(1)
#---------------------------------------# #---------------------------------------#
# Precomputations # # Precomputations #
#---------------------------------------# #---------------------------------------#
def _K_computations(self,X,X2): def _K_computations(self, X, X2):
if not (np.array_equal(X,self._X) and np.array_equal(X2,self._X2) and np.array_equal(self._params , self._get_params())): if not (np.array_equal(X, self._X) and np.array_equal(X2, self._X2) and np.array_equal(self._params , self._get_params())):
self._X = X.copy() self._X = X.copy()
self._params == self._get_params().copy() self._params == self._get_params().copy()
if X2 is None: if X2 is None:
self._X2 = None self._X2 = None
X = X/self.lengthscale X = X / self.lengthscale
Xsquare = np.sum(np.square(X),1) Xsquare = np.sum(np.square(X), 1)
self._K_dist2 = -2.*tdot(X) + (Xsquare[:,None] + Xsquare[None,:]) self._K_dist2 = -2.*tdot(X) + (Xsquare[:, None] + Xsquare[None, :])
else: else:
self._X2 = X2.copy() self._X2 = X2.copy()
X = X/self.lengthscale X = X / self.lengthscale
X2 = X2/self.lengthscale X2 = X2 / self.lengthscale
self._K_dist2 = -2.*np.dot(X, X2.T) + (np.sum(np.square(X),1)[:,None] + np.sum(np.square(X2),1)[None,:]) self._K_dist2 = -2.*np.dot(X, X2.T) + (np.sum(np.square(X), 1)[:, None] + np.sum(np.square(X2), 1)[None, :])
self._K_dvar = np.exp(-0.5*self._K_dist2) self._K_dvar = np.exp(-0.5 * self._K_dist2)
def _psi_computations(self,Z,mu,S): def _psi_computations(self, Z, mu, S):
#here are the "statistics" for psi1 and psi2 # here are the "statistics" for psi1 and psi2
if not np.array_equal(Z, self._Z): if not np.array_equal(Z, self._Z):
#Z has changed, compute Z specific stuff # Z has changed, compute Z specific stuff
self._psi2_Zhat = 0.5*(Z[:,None,:] +Z[None,:,:]) # M,M,input_dim self._psi2_Zhat = 0.5 * (Z[:, None, :] + Z[None, :, :]) # M,M,input_dim
self._psi2_Zdist = 0.5*(Z[:,None,:]-Z[None,:,:]) # M,M,input_dim self._psi2_Zdist = 0.5 * (Z[:, None, :] - Z[None, :, :]) # M,M,input_dim
self._psi2_Zdist_sq = np.square(self._psi2_Zdist/self.lengthscale) # M,M,input_dim self._psi2_Zdist_sq = np.square(self._psi2_Zdist / self.lengthscale) # M,M,input_dim
self._Z = Z self._Z = Z
if not (np.array_equal(Z, self._Z) and np.array_equal(mu, self._mu) and np.array_equal(S, self._S)): if not (np.array_equal(Z, self._Z) and np.array_equal(mu, self._mu) and np.array_equal(S, self._S)):
#something's changed. recompute EVERYTHING # something's changed. recompute EVERYTHING
#psi1 # psi1
self._psi1_denom = S[:,None,:]/self.lengthscale2 + 1. self._psi1_denom = S[:, None, :] / self.lengthscale2 + 1.
self._psi1_dist = Z[None,:,:]-mu[:,None,:] self._psi1_dist = Z[None, :, :] - mu[:, None, :]
self._psi1_dist_sq = np.square(self._psi1_dist)/self.lengthscale2/self._psi1_denom self._psi1_dist_sq = np.square(self._psi1_dist) / self.lengthscale2 / self._psi1_denom
self._psi1_exponent = -0.5*np.sum(self._psi1_dist_sq+np.log(self._psi1_denom),-1) self._psi1_exponent = -0.5 * np.sum(self._psi1_dist_sq + np.log(self._psi1_denom), -1)
self._psi1 = self.variance*np.exp(self._psi1_exponent) self._psi1 = self.variance * np.exp(self._psi1_exponent)
#psi2 # psi2
self._psi2_denom = 2.*S[:,None,None,:]/self.lengthscale2+1. # N,M,M,input_dim self._psi2_denom = 2.*S[:, None, None, :] / self.lengthscale2 + 1. # N,M,M,input_dim
self._psi2_mudist, self._psi2_mudist_sq, self._psi2_exponent, _ = self.weave_psi2(mu,self._psi2_Zhat) self._psi2_mudist, self._psi2_mudist_sq, self._psi2_exponent, _ = self.weave_psi2(mu, self._psi2_Zhat)
#self._psi2_mudist = mu[:,None,None,:]-self._psi2_Zhat #N,M,M,input_dim # self._psi2_mudist = mu[:,None,None,:]-self._psi2_Zhat #N,M,M,input_dim
#self._psi2_mudist_sq = np.square(self._psi2_mudist)/(self.lengthscale2*self._psi2_denom) # self._psi2_mudist_sq = np.square(self._psi2_mudist)/(self.lengthscale2*self._psi2_denom)
#self._psi2_exponent = np.sum(-self._psi2_Zdist_sq -self._psi2_mudist_sq -0.5*np.log(self._psi2_denom),-1) #N,M,M # self._psi2_exponent = np.sum(-self._psi2_Zdist_sq -self._psi2_mudist_sq -0.5*np.log(self._psi2_denom),-1) #N,M,M
self._psi2 = np.square(self.variance)*np.exp(self._psi2_exponent) # N,M,M self._psi2 = np.square(self.variance) * np.exp(self._psi2_exponent) # N,M,M
#store matrices for caching # store matrices for caching
self._Z, self._mu, self._S = Z, mu,S self._Z, self._mu, self._S = Z, mu, S
def weave_psi2(self,mu,Zhat): def weave_psi2(self, mu, Zhat):
N,input_dim = mu.shape N, input_dim = mu.shape
M = Zhat.shape[0] M = Zhat.shape[0]
mudist = np.empty((N,M,M,input_dim)) mudist = np.empty((N, M, M, input_dim))
mudist_sq = np.empty((N,M,M,input_dim)) mudist_sq = np.empty((N, M, M, input_dim))
psi2_exponent = np.zeros((N,M,M)) psi2_exponent = np.zeros((N, M, M))
psi2 = np.empty((N,M,M)) psi2 = np.empty((N, M, M))
psi2_Zdist_sq = self._psi2_Zdist_sq psi2_Zdist_sq = self._psi2_Zdist_sq
_psi2_denom = self._psi2_denom.squeeze().reshape(N,self.input_dim) _psi2_denom = self._psi2_denom.squeeze().reshape(N, self.input_dim)
half_log_psi2_denom = 0.5*np.log(self._psi2_denom).squeeze().reshape(N,self.input_dim) half_log_psi2_denom = 0.5 * np.log(self._psi2_denom).squeeze().reshape(N, self.input_dim)
variance_sq = float(np.square(self.variance)) variance_sq = float(np.square(self.variance))
if self.ARD: if self.ARD:
lengthscale2 = self.lengthscale2 lengthscale2 = self.lengthscale2
else: else:
lengthscale2 = np.ones(input_dim)*self.lengthscale2 lengthscale2 = np.ones(input_dim) * self.lengthscale2
code = """ code = """
double tmp; double tmp;
@ -325,7 +325,7 @@ class rbf(kernpart):
#include <math.h> #include <math.h>
""" """
weave.inline(code, support_code=support_code, libraries=['gomp'], weave.inline(code, support_code=support_code, libraries=['gomp'],
arg_names=['N','M','input_dim','mu','Zhat','mudist_sq','mudist','lengthscale2','_psi2_denom','psi2_Zdist_sq','psi2_exponent','half_log_psi2_denom','psi2','variance_sq'], arg_names=['N', 'M', 'input_dim', 'mu', 'Zhat', 'mudist_sq', 'mudist', 'lengthscale2', '_psi2_denom', 'psi2_Zdist_sq', 'psi2_exponent', 'half_log_psi2_denom', 'psi2', 'variance_sq'],
type_converters=weave.converters.blitz,**self.weave_options) type_converters=weave.converters.blitz, **self.weave_options)
return mudist,mudist_sq, psi2_exponent, psi2 return mudist, mudist_sq, psi2_exponent, psi2

View file

@ -7,26 +7,26 @@ from kernpart import kernpart
import numpy as np import numpy as np
class rbfcos(kernpart): class rbfcos(kernpart):
def __init__(self,D,variance=1.,frequencies=None,bandwidths=None,ARD=False): def __init__(self,input_dim,variance=1.,frequencies=None,bandwidths=None,ARD=False):
self.D = D self.input_dim = input_dim
self.name = 'rbfcos' self.name = 'rbfcos'
if self.D>10: if self.input_dim>10:
print "Warning: the rbfcos kernel requires a lot of memory for high dimensional inputs" print "Warning: the rbfcos kernel requires a lot of memory for high dimensional inputs"
self.ARD = ARD self.ARD = ARD
#set the default frequencies and bandwidths, appropriate Nparam #set the default frequencies and bandwidths, appropriate Nparam
if ARD: if ARD:
self.Nparam = 2*self.D + 1 self.Nparam = 2*self.input_dim + 1
if frequencies is not None: if frequencies is not None:
frequencies = np.asarray(frequencies) frequencies = np.asarray(frequencies)
assert frequencies.size == self.D, "bad number of frequencies" assert frequencies.size == self.input_dim, "bad number of frequencies"
else: else:
frequencies = np.ones(self.D) frequencies = np.ones(self.input_dim)
if bandwidths is not None: if bandwidths is not None:
bandwidths = np.asarray(bandwidths) bandwidths = np.asarray(bandwidths)
assert bandwidths.size == self.D, "bad number of bandwidths" assert bandwidths.size == self.input_dim, "bad number of bandwidths"
else: else:
bandwidths = np.ones(self.D) bandwidths = np.ones(self.input_dim)
else: else:
self.Nparam = 3 self.Nparam = 3
if frequencies is not None: if frequencies is not None:
@ -54,8 +54,8 @@ class rbfcos(kernpart):
assert x.size==(self.Nparam) assert x.size==(self.Nparam)
if self.ARD: if self.ARD:
self.variance = x[0] self.variance = x[0]
self.frequencies = x[1:1+self.D] self.frequencies = x[1:1+self.input_dim]
self.bandwidths = x[1+self.D:] self.bandwidths = x[1+self.input_dim:]
else: else:
self.variance, self.frequencies, self.bandwidths = x self.variance, self.frequencies, self.bandwidths = x
@ -63,7 +63,7 @@ class rbfcos(kernpart):
if self.Nparam == 3: if self.Nparam == 3:
return ['variance','frequency','bandwidth'] return ['variance','frequency','bandwidth']
else: else:
return ['variance']+['frequency_%i'%i for i in range(self.D)]+['bandwidth_%i'%i for i in range(self.D)] return ['variance']+['frequency_%i'%i for i in range(self.input_dim)]+['bandwidth_%i'%i for i in range(self.input_dim)]
def K(self,X,X2,target): def K(self,X,X2,target):
self._K_computations(X,X2) self._K_computations(X,X2)
@ -76,9 +76,9 @@ class rbfcos(kernpart):
self._K_computations(X,X2) self._K_computations(X,X2)
target[0] += np.sum(dL_dK*self._dvar) target[0] += np.sum(dL_dK*self._dvar)
if self.ARD: if self.ARD:
for q in xrange(self.D): for q in xrange(self.input_dim):
target[q+1] += -2.*np.pi*self.variance*np.sum(dL_dK*self._dvar*np.tan(2.*np.pi*self._dist[:,:,q]*self.frequencies[q])*self._dist[:,:,q]) target[q+1] += -2.*np.pi*self.variance*np.sum(dL_dK*self._dvar*np.tan(2.*np.pi*self._dist[:,:,q]*self.frequencies[q])*self._dist[:,:,q])
target[q+1+self.D] += -2.*np.pi**2*self.variance*np.sum(dL_dK*self._dvar*self._dist2[:,:,q]) target[q+1+self.input_dim] += -2.*np.pi**2*self.variance*np.sum(dL_dK*self._dvar*self._dist2[:,:,q])
else: else:
target[1] += -2.*np.pi*self.variance*np.sum(dL_dK*self._dvar*np.sum(np.tan(2.*np.pi*self._dist*self.frequencies)*self._dist,-1)) target[1] += -2.*np.pi*self.variance*np.sum(dL_dK*self._dvar*np.sum(np.tan(2.*np.pi*self._dist*self.frequencies)*self._dist,-1))
target[2] += -2.*np.pi**2*self.variance*np.sum(dL_dK*self._dvar*self._dist2.sum(-1)) target[2] += -2.*np.pi**2*self.variance*np.sum(dL_dK*self._dvar*self._dist2.sum(-1))
@ -100,7 +100,7 @@ class rbfcos(kernpart):
self._X = X.copy() self._X = X.copy()
self._X2 = X2.copy() self._X2 = X2.copy()
#do the distances: this will be high memory for large D #do the distances: this will be high memory for large input_dim
#NB: we don't take the abs of the dist because cos is symmetric #NB: we don't take the abs of the dist because cos is symmetric
self._dist = X[:,None,:] - X2[None,:,:] self._dist = X[:,None,:] - X2[None,:,:]
self._dist2 = np.square(self._dist) self._dist2 = np.square(self._dist)

View file

@ -13,16 +13,16 @@ class spline(kernpart):
""" """
Spline kernel Spline kernel
:param D: the number of input dimensions (fixed to 1 right now TODO) :param input_dim: the number of input dimensions (fixed to 1 right now TODO)
:type D: int :type input_dim: int
:param variance: the variance of the kernel :param variance: the variance of the kernel
:type variance: float :type variance: float
""" """
def __init__(self,D,variance=1.,lengthscale=1.): def __init__(self,input_dim,variance=1.,lengthscale=1.):
self.D = D self.input_dim = input_dim
assert self.D==1 assert self.input_dim==1
self.Nparam = 1 self.Nparam = 1
self.name = 'spline' self.name = 'spline'
self._set_params(np.squeeze(variance)) self._set_params(np.squeeze(variance))

View file

@ -11,16 +11,16 @@ class symmetric(kernpart):
:param k: the kernel to symmetrify :param k: the kernel to symmetrify
:type k: kernpart :type k: kernpart
:param transform: the transform to use in symmetrification (allows symmetry on specified axes) :param transform: the transform to use in symmetrification (allows symmetry on specified axes)
:type transform: A numpy array (D x D) specifiying the transform :type transform: A numpy array (input_dim x input_dim) specifiying the transform
:rtype: kernpart :rtype: kernpart
""" """
def __init__(self,k,transform=None): def __init__(self,k,transform=None):
if transform is None: if transform is None:
transform = np.eye(k.D)*-1. transform = np.eye(k.input_dim)*-1.
assert transform.shape == (k.D, k.D) assert transform.shape == (k.input_dim, k.input_dim)
self.transform = transform self.transform = transform
self.D = k.D self.input_dim = k.input_dim
self.Nparam = k.Nparam self.Nparam = k.Nparam
self.name = k.name + '_symm' self.name = k.name + '_symm'
self.k = k self.k = k

View file

@ -26,7 +26,7 @@ class spkern(kernpart):
- to handle multiple inputs, call them x1, z1, etc - to handle multiple inputs, call them x1, z1, etc
- to handle multpile correlated outputs, you'll need to define each covariance function and 'cross' variance function. TODO - to handle multpile correlated outputs, you'll need to define each covariance function and 'cross' variance function. TODO
""" """
def __init__(self,D,k,param=None): def __init__(self,input_dim,k,param=None):
self.name='sympykern' self.name='sympykern'
self._sp_k = k self._sp_k = k
sp_vars = [e for e in k.atoms() if e.is_Symbol] sp_vars = [e for e in k.atoms() if e.is_Symbol]
@ -35,8 +35,8 @@ class spkern(kernpart):
assert all([x.name=='x%i'%i for i,x in enumerate(self._sp_x)]) assert all([x.name=='x%i'%i for i,x in enumerate(self._sp_x)])
assert all([z.name=='z%i'%i for i,z in enumerate(self._sp_z)]) assert all([z.name=='z%i'%i for i,z in enumerate(self._sp_z)])
assert len(self._sp_x)==len(self._sp_z) assert len(self._sp_x)==len(self._sp_z)
self.D = len(self._sp_x) self.input_dim = len(self._sp_x)
assert self.D == D assert self.input_dim == input_dim
self._sp_theta = sorted([e for e in sp_vars if not (e.name[0]=='x' or e.name[0]=='z')],key=lambda e:e.name) self._sp_theta = sorted([e for e in sp_vars if not (e.name[0]=='x' or e.name[0]=='z')],key=lambda e:e.name)
self.Nparam = len(self._sp_theta) self.Nparam = len(self._sp_theta)
@ -69,15 +69,15 @@ class spkern(kernpart):
def compute_psi_stats(self): def compute_psi_stats(self):
#define some normal distributions #define some normal distributions
mus = [sp.var('mu%i'%i,real=True) for i in range(self.D)] mus = [sp.var('mu%i'%i,real=True) for i in range(self.input_dim)]
Ss = [sp.var('S%i'%i,positive=True) for i in range(self.D)] Ss = [sp.var('S%i'%i,positive=True) for i in range(self.input_dim)]
normals = [(2*sp.pi*Si)**(-0.5)*sp.exp(-0.5*(xi-mui)**2/Si) for xi, mui, Si in zip(self._sp_x, mus, Ss)] normals = [(2*sp.pi*Si)**(-0.5)*sp.exp(-0.5*(xi-mui)**2/Si) for xi, mui, Si in zip(self._sp_x, mus, Ss)]
#do some integration! #do some integration!
#self._sp_psi0 = ?? #self._sp_psi0 = ??
self._sp_psi1 = self._sp_k self._sp_psi1 = self._sp_k
for i in range(self.D): for i in range(self.input_dim):
print 'perfoming integrals %i of %i'%(i+1,2*self.D) print 'perfoming integrals %i of %i'%(i+1,2*self.input_dim)
sys.stdout.flush() sys.stdout.flush()
self._sp_psi1 *= normals[i] self._sp_psi1 *= normals[i]
self._sp_psi1 = sp.integrate(self._sp_psi1,(self._sp_x[i],-sp.oo,sp.oo)) self._sp_psi1 = sp.integrate(self._sp_psi1,(self._sp_x[i],-sp.oo,sp.oo))
@ -85,10 +85,10 @@ class spkern(kernpart):
self._sp_psi1 = self._sp_psi1.simplify() self._sp_psi1 = self._sp_psi1.simplify()
#and here's psi2 (eek!) #and here's psi2 (eek!)
zprime = [sp.Symbol('zp%i'%i) for i in range(self.D)] zprime = [sp.Symbol('zp%i'%i) for i in range(self.input_dim)]
self._sp_psi2 = self._sp_k.copy()*self._sp_k.copy().subs(zip(self._sp_z,zprime)) self._sp_psi2 = self._sp_k.copy()*self._sp_k.copy().subs(zip(self._sp_z,zprime))
for i in range(self.D): for i in range(self.input_dim):
print 'perfoming integrals %i of %i'%(self.D+i+1,2*self.D) print 'perfoming integrals %i of %i'%(self.input_dim+i+1,2*self.input_dim)
sys.stdout.flush() sys.stdout.flush()
self._sp_psi2 *= normals[i] self._sp_psi2 *= normals[i]
self._sp_psi2 = sp.integrate(self._sp_psi2,(self._sp_x[i],-sp.oo,sp.oo)) self._sp_psi2 = sp.integrate(self._sp_psi2,(self._sp_x[i],-sp.oo,sp.oo))
@ -113,8 +113,8 @@ class spkern(kernpart):
self._function_code = re.sub('DiracDelta\(.+?,.+?\)','0.0',self._function_code) self._function_code = re.sub('DiracDelta\(.+?,.+?\)','0.0',self._function_code)
#Here's some code to do the looping for K #Here's some code to do the looping for K
arglist = ", ".join(["X[i*D+%s]"%x.name[1:] for x in self._sp_x]\ arglist = ", ".join(["X[i*input_dim+%s]"%x.name[1:] for x in self._sp_x]\
+ ["Z[j*D+%s]"%z.name[1:] for z in self._sp_z]\ + ["Z[j*input_dim+%s]"%z.name[1:] for z in self._sp_z]\
+ ["param[%i]"%i for i in range(self.Nparam)]) + ["param[%i]"%i for i in range(self.Nparam)])
self._K_code =\ self._K_code =\
@ -123,7 +123,7 @@ class spkern(kernpart):
int j; int j;
int N = target_array->dimensions[0]; int N = target_array->dimensions[0];
int M = target_array->dimensions[1]; int M = target_array->dimensions[1];
int D = X_array->dimensions[1]; int input_dim = X_array->dimensions[1];
//#pragma omp parallel for private(j) //#pragma omp parallel for private(j)
for (i=0;i<N;i++){ for (i=0;i<N;i++){
for (j=0;j<M;j++){ for (j=0;j<M;j++){
@ -140,7 +140,7 @@ class spkern(kernpart):
""" """
int i; int i;
int N = target_array->dimensions[0]; int N = target_array->dimensions[0];
int D = X_array->dimensions[1]; int input_dim = X_array->dimensions[1];
//#pragma omp parallel for //#pragma omp parallel for
for (i=0;i<N;i++){ for (i=0;i<N;i++){
target[i] = k(%s); target[i] = k(%s);
@ -156,7 +156,7 @@ class spkern(kernpart):
int j; int j;
int N = partial_array->dimensions[0]; int N = partial_array->dimensions[0];
int M = partial_array->dimensions[1]; int M = partial_array->dimensions[1];
int D = X_array->dimensions[1]; int input_dim = X_array->dimensions[1];
//#pragma omp parallel for private(j) //#pragma omp parallel for private(j)
for (i=0;i<N;i++){ for (i=0;i<N;i++){
for (j=0;j<M;j++){ for (j=0;j<M;j++){
@ -174,7 +174,7 @@ class spkern(kernpart):
""" """
int i; int i;
int N = partial_array->dimensions[0]; int N = partial_array->dimensions[0];
int D = X_array->dimensions[1]; int input_dim = X_array->dimensions[1];
for (i=0;i<N;i++){ for (i=0;i<N;i++){
%s %s
} }
@ -182,20 +182,20 @@ class spkern(kernpart):
"""%(diag_funclist,"/*"+str(self._sp_k)+"*/") #adding a string representation forces recompile when needed """%(diag_funclist,"/*"+str(self._sp_k)+"*/") #adding a string representation forces recompile when needed
#Here's some code to do gradients wrt x #Here's some code to do gradients wrt x
gradient_funcs = "\n".join(["target[i*D+%i] += partial[i*M+j]*dk_dx%i(%s);"%(q,q,arglist) for q in range(self.D)]) gradient_funcs = "\n".join(["target[i*input_dim+%i] += partial[i*M+j]*dk_dx%i(%s);"%(q,q,arglist) for q in range(self.input_dim)])
self._dK_dX_code = \ self._dK_dX_code = \
""" """
int i; int i;
int j; int j;
int N = partial_array->dimensions[0]; int N = partial_array->dimensions[0];
int M = partial_array->dimensions[1]; int M = partial_array->dimensions[1];
int D = X_array->dimensions[1]; int input_dim = X_array->dimensions[1];
//#pragma omp parallel for private(j) //#pragma omp parallel for private(j)
for (i=0;i<N; i++){ for (i=0;i<N; i++){
for (j=0; j<M; j++){ for (j=0; j<M; j++){
%s %s
//if(isnan(target[i*D+2])){printf("%%f\\n",dk_dx2(X[i*D+0], X[i*D+1], X[i*D+2], Z[j*D+0], Z[j*D+1], Z[j*D+2], param[0], param[1], param[2], param[3], param[4], param[5]));} //if(isnan(target[i*input_dim+2])){printf("%%f\\n",dk_dx2(X[i*input_dim+0], X[i*input_dim+1], X[i*input_dim+2], Z[j*input_dim+0], Z[j*input_dim+1], Z[j*input_dim+2], param[0], param[1], param[2], param[3], param[4], param[5]));}
//if(isnan(target[i*D+2])){printf("%%f,%%f,%%i,%%i\\n", X[i*D+2], Z[j*D+2],i,j);} //if(isnan(target[i*input_dim+2])){printf("%%f,%%f,%%i,%%i\\n", X[i*input_dim+2], Z[j*input_dim+2],i,j);}
} }
} }
@ -209,7 +209,7 @@ class spkern(kernpart):
int j; int j;
int N = partial_array->dimensions[0]; int N = partial_array->dimensions[0];
int M = 0; int M = 0;
int D = X_array->dimensions[1]; int input_dim = X_array->dimensions[1];
for (i=0;i<N; i++){ for (i=0;i<N; i++){
j = i; j = i;
%s %s