Merge branch 'devel' of github.com:SheffieldML/GPy into devel

This commit is contained in:
James Hensman 2013-06-04 17:19:44 +01:00
commit e29e5624f5
7 changed files with 263 additions and 163 deletions

View file

@ -14,6 +14,7 @@ import priors
import re
import sys
import pdb
from GPy.core.domains import POSITIVE, REAL
# import numdifftools as ndt
class model(parameterised):
@ -68,8 +69,9 @@ class model(parameterised):
# check constraints are okay
if isinstance(what, (priors.gamma, priors.inverse_gamma, priors.log_Gaussian)):
constrained_positive_indices = [i for i, t in zip(self.constrained_indices, self.constraints) if t.domain == 'positive']
if what.domain is POSITIVE:
constrained_positive_indices = [i for i, t in zip(self.constrained_indices, self.constraints) if t.domain == POSITIVE]
if len(constrained_positive_indices):
constrained_positive_indices = np.hstack(constrained_positive_indices)
else:
@ -82,7 +84,7 @@ class model(parameterised):
print '\n'.join([n for i, n in enumerate(self._get_param_names()) if i in unconst])
print '\n'
self.constrain_positive(unconst)
elif isinstance(what, priors.Gaussian):
elif what.domain is REAL:
assert not np.any(which[:, None] == self.all_constrained_indices()), "constraint and prior incompatible"
else:
raise ValueError, "prior not recognised"

View file

@ -6,17 +6,20 @@ import numpy as np
import pylab as pb
from scipy.special import gammaln, digamma
from ..util.linalg import pdinv
from GPy.core.domains import REAL, POSITIVE
import warnings
class prior:
def pdf(self,x):
domain = None
def pdf(self, x):
return np.exp(self.lnpdf(x))
def plot(self):
rvs = self.rvs(1000)
pb.hist(rvs,100,normed=True)
xmin,xmax = pb.xlim()
xx = np.linspace(xmin,xmax,1000)
pb.plot(xx,self.pdf(xx),'r',linewidth=2)
pb.hist(rvs, 100, normed=True)
xmin, xmax = pb.xlim()
xx = np.linspace(xmin, xmax, 1000)
pb.plot(xx, self.pdf(xx), 'r', linewidth=2)
class Gaussian(prior):
@ -29,24 +32,24 @@ class Gaussian(prior):
.. Note:: Bishop 2006 notation is used throughout the code
"""
def __init__(self,mu,sigma):
domain = REAL
def __init__(self, mu, sigma):
self.mu = float(mu)
self.sigma = float(sigma)
self.sigma2 = np.square(self.sigma)
self.constant = -0.5*np.log(2*np.pi*self.sigma2)
self.constant = -0.5 * np.log(2 * np.pi * self.sigma2)
def __str__(self):
return "N("+str(np.round(self.mu))+', '+str(np.round(self.sigma2))+')'
return "N(" + str(np.round(self.mu)) + ', ' + str(np.round(self.sigma2)) + ')'
def lnpdf(self,x):
return self.constant - 0.5*np.square(x-self.mu)/self.sigma2
def lnpdf(self, x):
return self.constant - 0.5 * np.square(x - self.mu) / self.sigma2
def lnpdf_grad(self,x):
return -(x-self.mu)/self.sigma2
def lnpdf_grad(self, x):
return -(x - self.mu) / self.sigma2
def rvs(self,n):
return np.random.randn(n)*self.sigma + self.mu
def rvs(self, n):
return np.random.randn(n) * self.sigma + self.mu
class log_Gaussian(prior):
@ -59,24 +62,24 @@ class log_Gaussian(prior):
.. Note:: Bishop 2006 notation is used throughout the code
"""
def __init__(self,mu,sigma):
domain = POSITIVE
def __init__(self, mu, sigma):
self.mu = float(mu)
self.sigma = float(sigma)
self.sigma2 = np.square(self.sigma)
self.constant = -0.5*np.log(2*np.pi*self.sigma2)
self.constant = -0.5 * np.log(2 * np.pi * self.sigma2)
def __str__(self):
return "lnN("+str(np.round(self.mu))+', '+str(np.round(self.sigma2))+')'
return "lnN(" + str(np.round(self.mu)) + ', ' + str(np.round(self.sigma2)) + ')'
def lnpdf(self,x):
return self.constant - 0.5*np.square(np.log(x)-self.mu)/self.sigma2 -np.log(x)
def lnpdf(self, x):
return self.constant - 0.5 * np.square(np.log(x) - self.mu) / self.sigma2 - np.log(x)
def lnpdf_grad(self,x):
return -((np.log(x)-self.mu)/self.sigma2+1.)/x
def lnpdf_grad(self, x):
return -((np.log(x) - self.mu) / self.sigma2 + 1.) / x
def rvs(self,n):
return np.exp(np.random.randn(n)*self.sigma + self.mu)
def rvs(self, n):
return np.exp(np.random.randn(n) * self.sigma + self.mu)
class multivariate_Gaussian:
@ -89,47 +92,47 @@ class multivariate_Gaussian:
.. Note:: Bishop 2006 notation is used throughout the code
"""
def __init__(self,mu,var):
domain = REAL
def __init__(self, mu, var):
self.mu = np.array(mu).flatten()
self.var = np.array(var)
assert len(self.var.shape)==2
assert self.var.shape[0]==self.var.shape[1]
assert self.var.shape[0]==self.mu.size
assert len(self.var.shape) == 2
assert self.var.shape[0] == self.var.shape[1]
assert self.var.shape[0] == self.mu.size
self.D = self.mu.size
self.inv, self.hld = pdinv(self.var)
self.constant = -0.5*self.D*np.log(2*np.pi) - self.hld
self.constant = -0.5 * self.D * np.log(2 * np.pi) - self.hld
def summary(self):
raise NotImplementedError
def pdf(self,x):
def pdf(self, x):
return np.exp(self.lnpdf(x))
def lnpdf(self,x):
d = x-self.mu
return self.constant - 0.5*np.sum(d*np.dot(d,self.inv),1)
def lnpdf(self, x):
d = x - self.mu
return self.constant - 0.5 * np.sum(d * np.dot(d, self.inv), 1)
def lnpdf_grad(self,x):
d = x-self.mu
return -np.dot(self.inv,d)
def lnpdf_grad(self, x):
d = x - self.mu
return -np.dot(self.inv, d)
def rvs(self,n):
return np.random.multivariate_normal(self.mu, self.var,n)
def rvs(self, n):
return np.random.multivariate_normal(self.mu, self.var, n)
def plot(self):
if self.D==2:
if self.D == 2:
rvs = self.rvs(200)
pb.plot(rvs[:,0],rvs[:,1], 'kx', mew=1.5)
xmin,xmax = pb.xlim()
ymin,ymax = pb.ylim()
pb.plot(rvs[:, 0], rvs[:, 1], 'kx', mew=1.5)
xmin, xmax = pb.xlim()
ymin, ymax = pb.ylim()
xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
xflat = np.vstack((xx.flatten(),yy.flatten())).T
zz = self.pdf(xflat).reshape(100,100)
pb.contour(xx,yy,zz,linewidths=2)
xflat = np.vstack((xx.flatten(), yy.flatten())).T
zz = self.pdf(xflat).reshape(100, 100)
pb.contour(xx, yy, zz, linewidths=2)
def gamma_from_EV(E,V):
def gamma_from_EV(E, V):
"""
Creates an instance of a gamma prior by specifying the Expected value(s)
and Variance(s) of the distribution.
@ -138,10 +141,10 @@ def gamma_from_EV(E,V):
:param V: variance
"""
a = np.square(E)/V
b = E/V
return gamma(a,b)
warnings.warn("use Gamma.from_EV to create Gamma Prior", FutureWarning)
a = np.square(E) / V
b = E / V
return gamma(a, b)
class gamma(prior):
"""
@ -153,33 +156,34 @@ class gamma(prior):
.. Note:: Bishop 2006 notation is used throughout the code
"""
def __init__(self,a,b):
domain = POSITIVE
def __init__(self, a, b):
self.a = float(a)
self.b = float(b)
self.constant = -gammaln(self.a) + a*np.log(b)
self.constant = -gammaln(self.a) + a * np.log(b)
def __str__(self):
return "Ga("+str(np.round(self.a))+', '+str(np.round(self.b))+')'
return "Ga(" + str(np.round(self.a)) + ', ' + str(np.round(self.b)) + ')'
def summary(self):
ret = {"E[x]": self.a/self.b,\
"E[ln x]": digamma(self.a) - np.log(self.b),\
"var[x]": self.a/self.b/self.b,\
"Entropy": gammaln(self.a) - (self.a-1.)*digamma(self.a) - np.log(self.b) + self.a}
if self.a >1:
ret['Mode'] = (self.a-1.)/self.b
ret = {"E[x]": self.a / self.b, \
"E[ln x]": digamma(self.a) - np.log(self.b), \
"var[x]": self.a / self.b / self.b, \
"Entropy": gammaln(self.a) - (self.a - 1.) * digamma(self.a) - np.log(self.b) + self.a}
if self.a > 1:
ret['Mode'] = (self.a - 1.) / self.b
else:
ret['mode'] = np.nan
return ret
def lnpdf(self,x):
return self.constant + (self.a-1)*np.log(x) - self.b*x
def lnpdf(self, x):
return self.constant + (self.a - 1) * np.log(x) - self.b * x
def lnpdf_grad(self,x):
return (self.a-1.)/x - self.b
def lnpdf_grad(self, x):
return (self.a - 1.) / x - self.b
def rvs(self,n):
return np.random.gamma(scale=1./self.b,shape=self.a,size=n)
def rvs(self, n):
return np.random.gamma(scale=1. / self.b, shape=self.a, size=n)
class inverse_gamma(prior):
"""
@ -191,19 +195,20 @@ class inverse_gamma(prior):
.. Note:: Bishop 2006 notation is used throughout the code
"""
def __init__(self,a,b):
domain = POSITIVE
def __init__(self, a, b):
self.a = float(a)
self.b = float(b)
self.constant = -gammaln(self.a) + a*np.log(b)
self.constant = -gammaln(self.a) + a * np.log(b)
def __str__(self):
return "iGa("+str(np.round(self.a))+', '+str(np.round(self.b))+')'
return "iGa(" + str(np.round(self.a)) + ', ' + str(np.round(self.b)) + ')'
def lnpdf(self,x):
return self.constant - (self.a+1)*np.log(x) - self.b/x
def lnpdf(self, x):
return self.constant - (self.a + 1) * np.log(x) - self.b / x
def lnpdf_grad(self,x):
return -(self.a+1.)/x + self.b/x**2
def lnpdf_grad(self, x):
return -(self.a + 1.) / x + self.b / x ** 2
def rvs(self,n):
return 1./np.random.gamma(scale=1./self.b,shape=self.a,size=n)
def rvs(self, n):
return 1. / np.random.gamma(scale=1. / self.b, shape=self.a, size=n)

View file

@ -3,11 +3,10 @@
import numpy as np
from GPy.core.domains import POSITIVE, NEGATIVE, BOUNDED
class transformation(object):
def __init__(self):
# set the domain. Suggest we use 'positive', 'bounded', etc
self.domain = 'undefined'
domain = None
def f(self, x):
raise NotImplementedError
@ -24,8 +23,7 @@ class transformation(object):
raise NotImplementedError
class logexp(transformation):
def __init__(self):
self.domain = 'positive'
domain = POSITIVE
def f(self, x):
return np.log(1. + np.exp(x))
def finv(self, f):
@ -43,8 +41,8 @@ class logexp_clipped(transformation):
min_bound = 1e-10
log_max_bound = np.log(max_bound)
log_min_bound = np.log(min_bound)
domain = POSITIVE
def __init__(self, lower=1e-6):
self.domain = 'positive'
self.lower = lower
def f(self, x):
exp = np.exp(np.clip(x, self.log_min_bound, self.log_max_bound))
@ -66,8 +64,7 @@ class logexp_clipped(transformation):
return '(+ve_c)'
class exponent(transformation):
def __init__(self):
self.domain = 'positive'
domain = POSITIVE
def f(self, x):
return np.exp(x)
def finv(self, x):
@ -82,8 +79,7 @@ class exponent(transformation):
return '(+ve)'
class negative_exponent(transformation):
def __init__(self):
self.domain = 'negative'
domain = NEGATIVE
def f(self, x):
return -np.exp(x)
def finv(self, x):
@ -98,8 +94,7 @@ class negative_exponent(transformation):
return '(-ve)'
class square(transformation):
def __init__(self):
self.domain = 'positive'
domain = POSITIVE
def f(self, x):
return x ** 2
def finv(self, x):
@ -112,8 +107,8 @@ class square(transformation):
return '(+sq)'
class logistic(transformation):
domain = BOUNDED
def __init__(self, lower, upper):
self.domain = 'bounded'
assert lower < upper
self.lower, self.upper = float(lower), float(upper)
self.difference = self.upper - self.lower