INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Example of regressing with a student t likelihood using Laplace | def student_t_approx(optimize=True, plot=True):
"""
Example of regressing with a student t likelihood using Laplace
"""
real_std = 0.1
#Start a function, any function
X = np.linspace(0.0, np.pi*2, 100)[:, None]
Y = np.sin(X) + np.random.randn(*X.shape)*real_std
Y = Y/Y.max()
Yc = Y.c... |
Return covariance between X and X2. | def K(self, X, X2, target):
"""Return covariance between X and X2."""
self._K_computations(X, X2)
target += self.variance*self._K_dvar |
Compute the diagonal of the covariance matrix for X. | def Kdiag(self, X, target):
"""Compute the diagonal of the covariance matrix for X."""
self._K_diag_computations(X)
target+= self.variance*self._K_diag_dvar |
Derivative of the covariance with respect to the parameters. | def _param_grad_helper(self, dL_dK, X, X2, target):
"""Derivative of the covariance with respect to the parameters."""
self._K_computations(X, X2)
base = self.variance*self.degree*self._K_poly_arg**(self.degree-1)
base_cov_grad = base*dL_dK
target[0] += np.sum(self... |
Derivative of the covariance matrix with respect to X | def gradients_X(self, dL_dK, X, X2, target):
"""Derivative of the covariance matrix with respect to X"""
self._K_computations(X, X2)
arg = self._K_poly_arg
if X2 is None:
target += 2*self.weight_variance*self.degree*self.variance*(((X[None,:, :])) *(arg**(self.degree-1))[:, :... |
Gradient of diagonal of covariance with respect to X | def dKdiag_dX(self, dL_dKdiag, X, target):
"""Gradient of diagonal of covariance with respect to X"""
self._K_diag_computations(X)
arg = self._K_diag_poly_arg
target += 2.*self.weight_variance*self.degree*self.variance*X*dL_dKdiag[:, None]*(arg**(self.degree-1))[:, None] |
If an ARD kernel is present plot a bar representation using matplotlib | def plot_ARD(kernel, filtering=None, legend=False, canvas=None, **kwargs):
"""
If an ARD kernel is present, plot a bar representation using matplotlib
:param fignum: figure number of the plot
:param filtering: list of names, which to use for plotting ARD parameters.
Only kernels w... |
Plot a kernel covariance w. r. t. another x. | def plot_covariance(kernel, x=None, label=None,
plot_limits=None, visible_dims=None, resolution=None,
projection='2d', levels=20, **kwargs):
"""
Plot a kernel covariance w.r.t. another x.
:param array-like x: the value to use for the other kernel argument (kernels are a function o... |
Instantiate an object of a derived class using the information in input_dict ( built by the to_dict method of the derived class ). More specifically after reading the derived class from input_dict it calls the method _build_from_input_dict of the derived class. Note: This method should not be overrided in the derived c... | def from_dict(input_dict):
"""
Instantiate an object of a derived class using the information
in input_dict (built by the to_dict method of the derived class).
More specifically, after reading the derived class from input_dict,
it calls the method _build_from_input_dict of the de... |
Run a standard Gaussian process regression on the Olympic marathon data. | def olympic_marathon_men(optimize=True, plot=True):
"""Run a standard Gaussian process regression on the Olympic marathon data."""
try:import pods
except ImportError:
print('pods unavailable, see https://github.com/sods/ods for example datasets')
return
data = pods.datasets.olympic_marat... |
A simple demonstration of coregionalization on two sinusoidal functions. | def coregionalization_toy(optimize=True, plot=True):
"""
A simple demonstration of coregionalization on two sinusoidal functions.
"""
#build a design matrix with a column of integers indicating the output
X1 = np.random.rand(50, 1) * 8
X2 = np.random.rand(30, 1) * 5
#build a suitable set of... |
Perform Gaussian process regression on the latitude and longitude data from the Mount Epomeo runs. Requires gpxpy to be installed on your system to load in the data. | def epomeo_gpx(max_iters=200, optimize=True, plot=True):
"""
Perform Gaussian process regression on the latitude and longitude data
from the Mount Epomeo runs. Requires gpxpy to be installed on your system
to load in the data.
"""
try:import pods
except ImportError:
print('pods unava... |
Show an example of a multimodal error surface for Gaussian process regression. Gene 939 has bimodal behaviour where the noisy mode is higher. | def multiple_optima(gene_number=937, resolution=80, model_restarts=10, seed=10000, max_iters=300, optimize=True, plot=True):
"""
Show an example of a multimodal error surface for Gaussian process
regression. Gene 939 has bimodal behaviour where the noisy mode is
higher.
"""
# Contour over a ran... |
Evaluate the GP objective function for a given data set for a range of signal to noise ratios and a range of lengthscales. | def _contour_data(data, length_scales, log_SNRs, kernel_call=GPy.kern.RBF):
"""
Evaluate the GP objective function for a given data set for a range of
signal to noise ratios and a range of lengthscales.
:data_set: A data set from the utils.datasets director.
:length_scales: a list of length scales ... |
Run a standard Gaussian process regression on the Rogers and Girolami olympics data. | def olympic_100m_men(optimize=True, plot=True):
"""Run a standard Gaussian process regression on the Rogers and Girolami olympics data."""
try:import pods
except ImportError:
print('pods unavailable, see https://github.com/sods/ods for example datasets')
return
data = pods.datasets.olymp... |
Run a simple demonstration of a standard Gaussian process fitting it to data sampled from an RBF covariance. | def toy_rbf_1d(optimize=True, plot=True):
"""Run a simple demonstration of a standard Gaussian process fitting it to data sampled from an RBF covariance."""
try:import pods
except ImportError:
print('pods unavailable, see https://github.com/sods/ods for example datasets')
return
data = p... |
Run a simple demonstration of a standard Gaussian process fitting it to data sampled from an RBF covariance. | def toy_poisson_rbf_1d_laplace(optimize=True, plot=True):
"""Run a simple demonstration of a standard Gaussian process fitting it to data sampled from an RBF covariance."""
optimizer='scg'
x_len = 100
X = np.linspace(0, 10, x_len)[:, None]
f_true = np.random.multivariate_normal(np.zeros(x_len), GPy.... |
Predict the location of a robot given wirelss signal strength readings. | def robot_wireless(max_iters=100, kernel=None, optimize=True, plot=True):
"""Predict the location of a robot given wirelss signal strength readings."""
try:import pods
except ImportError:
print('pods unavailable, see https://github.com/sods/ods for example datasets')
return
data = pods.d... |
Predict the pose of a figure given a silhouette. This is a task from Agarwal and Triggs 2004 ICML paper. | def silhouette(max_iters=100, optimize=True, plot=True):
"""Predict the pose of a figure given a silhouette. This is a task from Agarwal and Triggs 2004 ICML paper."""
try:import pods
except ImportError:
print('pods unavailable, see https://github.com/sods/ods for example datasets')
return
... |
Run a 1D example of a sparse GP regression. | def sparse_GP_regression_1D(num_samples=400, num_inducing=5, max_iters=100, optimize=True, plot=True, checkgrad=False):
"""Run a 1D example of a sparse GP regression."""
# sample inputs and outputs
X = np.random.uniform(-3., 3., (num_samples, 1))
Y = np.sin(X) + np.random.randn(num_samples, 1) * 0.05
... |
Run a 2D example of a sparse GP regression. | def sparse_GP_regression_2D(num_samples=400, num_inducing=50, max_iters=100, optimize=True, plot=True, nan=False):
"""Run a 2D example of a sparse GP regression."""
np.random.seed(1234)
X = np.random.uniform(-3., 3., (num_samples, 2))
Y = np.sin(X[:, 0:1]) * np.sin(X[:, 1:2]) + np.random.randn(num_sampl... |
Run a 1D example of a sparse GP regression with uncertain inputs. | def uncertain_inputs_sparse_regression(max_iters=200, optimize=True, plot=True):
"""Run a 1D example of a sparse GP regression with uncertain inputs."""
fig, axes = pb.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True)
# sample inputs and outputs
S = np.ones((20, 1))
X = np.random.uniform(-3... |
The simplest possible mean function. No parameters just a simple Sinusoid. | def simple_mean_function(max_iters=100, optimize=True, plot=True):
"""
The simplest possible mean function. No parameters, just a simple Sinusoid.
"""
#create simple mean function
mf = GPy.core.Mapping(1,1)
mf.f = np.sin
mf.update_gradients = lambda a,b: None
X = np.linspace(0,10,50).r... |
A linear mean function with parameters that we ll learn alongside the kernel | def parametric_mean_function(max_iters=100, optimize=True, plot=True):
"""
A linear mean function with parameters that we'll learn alongside the kernel
"""
#create simple mean function
mf = GPy.core.Mapping(1,1)
mf.f = np.sin
X = np.linspace(0,10,50).reshape(-1,1)
Y = np.sin(X) + 0.5*n... |
A test replicating the cubic sine regression problem from Snelson s paper. | def warped_gp_cubic_sine(max_iters=100):
"""
A test replicating the cubic sine regression problem from
Snelson's paper.
"""
X = (2 * np.pi) * np.random.random(151) - np.pi
Y = np.sin(X) + np.random.normal(0,0.2,151)
Y = np.array([np.power(abs(y),float(1)/3) * (1,-1)[y<0] for y in Y])
X =... |
Return the predictive mean and variance at a series of new points X1new X2new Only returns the diagonal of the predictive variance for now. | def predict(self, X1new, X2new):
"""
Return the predictive mean and variance at a series of new points X1new, X2new
Only returns the diagonal of the predictive variance, for now.
:param X1new: The points at which to make a prediction
:type X1new: np.ndarray, Nnew x self.input_di... |
Make the right decisions for prediction with a model based on the standard arguments of plotting. | def helper_predict_with_model(self, Xgrid, plot_raw, apply_link, percentiles, which_data_ycols, predict_kw, samples=0):
"""
Make the right decisions for prediction with a model
based on the standard arguments of plotting.
This is quite complex and will take a while to understand,
so do not change a... |
Figure out the data free_dims and create an Xgrid for the prediction. | def helper_for_plot_data(self, X, plot_limits, visible_dims, fixed_inputs, resolution):
"""
Figure out the data, free_dims and create an Xgrid for
the prediction.
This is only implemented for two dimensions for now!
"""
#work out what the inputs are for plotting (1D or 2D)
if fixed_inputs i... |
Stratified subsampling if labels are given. This means due to rounding errors you might get a little differences between the num_samples and the returned subsampled X. | def subsample_X(X, labels, num_samples=1000):
"""
Stratified subsampling if labels are given.
This means due to rounding errors you might get a little differences between the
num_samples and the returned subsampled X.
"""
if X.shape[0] > num_samples:
print("Warning: subsampling X, as it ... |
This function updates the keyword aguments from update_from in to_update only if the keys are not set in to_update. | def update_not_existing_kwargs(to_update, update_from):
"""
This function updates the keyword aguments from update_from in
to_update, only if the keys are not set in to_update.
This is used for updated kwargs from the default dicts.
"""
if to_update is None:
to_update = {}
to_update... |
Either the the data from a model as X the inputs X_variance the variance of the inputs ( [ default: None ] ) and Y the outputs | def get_x_y_var(model):
"""
Either the the data from a model as
X the inputs,
X_variance the variance of the inputs ([default: None])
and Y the outputs
If (X, X_variance, Y) is given, this just returns.
:returns: (X, X_variance, Y)
"""
# model given
if hasattr(model, 'has_uncer... |
work out what the inputs are for plotting ( 1D or 2D ) | def get_free_dims(model, visible_dims, fixed_dims):
"""
work out what the inputs are for plotting (1D or 2D)
The visible dimensions are the dimensions, which are visible.
the fixed_dims are the fixed dimensions for this.
The free_dims are then the visible dims without the fixed dims.
"""
i... |
Helper to get the data columns to plot. | def get_which_data_ycols(model, which_data_ycols):
"""
Helper to get the data columns to plot.
"""
if which_data_ycols == 'all' or which_data_ycols is None:
return np.arange(model.output_dim)
return which_data_ycols |
Internal helper function for making plots returns a set of input values to plot as well as lower and upper limits | def x_frame1D(X,plot_limits=None,resolution=None):
"""
Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits
"""
assert X.shape[1] ==1, "x_frame1D is defined for one-dimensional inputs"
if plot_limits is None:
from GPy.core.paramet... |
Internal helper function for making plots returns a set of input values to plot as well as lower and upper limits | def x_frame2D(X,plot_limits=None,resolution=None):
"""
Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits
"""
assert X.shape[1]==2, "x_frame2D is defined for two-dimensional inputs"
if plot_limits is None:
xmin, xmax = X.min(0),... |
Center X in PCA space. | def center(self, X):
"""
Center `X` in PCA space.
"""
X = X.copy()
inan = numpy.isnan(X)
if self.mu is None:
X_ = numpy.ma.masked_array(X, inan)
self.mu = X_.mean(0).base
self.sigma = X_.std(0).base
reduce(lambda y,x: setitem(x[... |
Project X into PCA space defined by the Q highest eigenvalues. Y = X dot V | def project(self, X, Q=None):
"""
Project X into PCA space, defined by the Q highest eigenvalues.
Y = X dot V
"""
if Q is None:
Q = self.Q
if Q > X.shape[1]:
raise IndexError("requested dimension larger then input dimension")
X = self.cente... |
Plot fractions of Eigenvalues sorted in descending order. | def plot_fracs(self, Q=None, ax=None, fignum=None):
"""
Plot fractions of Eigenvalues sorted in descending order.
"""
from ..plotting import Tango
Tango.reset()
col = Tango.nextMedium()
if ax is None:
fig = pylab.figure(fignum)
ax = fig.add... |
Plot dimensions dimensions with given labels against each other in PC space. Labels can be any sequence of labels of dimensions X. shape [ 0 ]. Labels can be drawn with a subsequent call to legend () | def plot_2d(self, X, labels=None, s=20, marker='o',
dimensions=(0, 1), ax=None, colors=None,
fignum=None, cmap=None, # @UndefinedVariable
** kwargs):
"""
Plot dimensions `dimensions` with given labels against each other in
PC space. Labels can be a... |
Plot a scatter plot of the latent space. | def plot_latent_scatter(self, labels=None,
which_indices=None,
legend=True,
plot_limits=None,
marker='<>^vsd',
num_samples=1000,
projection='2d',
**kwar... |
Plot a scatter plot of the inducing inputs. | def plot_latent_inducing(self,
which_indices=None,
legend=False,
plot_limits=None,
marker=None,
projection='2d',
**kwargs):
"""
Plot a scatter plot of the inducing inpu... |
Plot the magnification factor of the GP on the inputs. This is the density of the GP as a gray scale. | def plot_magnification(self, labels=None, which_indices=None,
resolution=60, marker='<>^vsd', legend=True,
plot_limits=None,
updates=False,
mean=True, covariance=True,
kern=None, num_samples=1000,
scatter_kwargs=None, plot_s... |
Plot the latent space of the GP on the inputs. This is the density of the GP posterior as a grey scale and the scatter plot of the input dimemsions selected by which_indices. | def plot_latent(self, labels=None, which_indices=None,
resolution=60, legend=True,
plot_limits=None,
updates=False,
kern=None, marker='<>^vsd',
num_samples=1000, projection='2d',
scatter_kwargs=None, **imshow_kwargs):
""... |
Plot the latent space of the GP on the inputs. This is the density of the GP posterior as a grey scale and the scatter plot of the input dimemsions selected by which_indices. | def plot_steepest_gradient_map(self, output_labels=None, data_labels=None, which_indices=None,
resolution=15, legend=True,
plot_limits=None,
updates=False,
kern=None, marker='<>^vsd',
num_samples=1000,
annotation_kwargs=None... |
This method is overwritten because we need to modify kdiag by substituting z for x. We do this by calling the parent expression method to extract variables from expressions then subsitute the z variables that are present with x. | def _set_expressions(self, expressions):
"""This method is overwritten because we need to modify kdiag by substituting z for x. We do this by calling the parent expression method to extract variables from expressions, then subsitute the z variables that are present with x."""
Symbolic_core._set_expressi... |
The function computes matrix exponent and handles some special cases | def matrix_exponent(M):
"""
The function computes matrix exponent and handles some special cases
"""
if (M.shape[0] == 1): # 1*1 matrix
Mexp = np.array( ((np.exp(M[0,0]) ,),) )
else: # matrix is larger
method = None
try:
Mexp = linalg.expm(M)
method ... |
Balance matrix i. e. finds such similarity transformation of the original matrix A: A = T * bA * T^ { - 1 } where norms of columns of bA and of rows of bA are as close as possible. It is usually used as a preprocessing step in eigenvalue calculation routine. It is useful also for State - Space models. | def balance_matrix(A):
"""
Balance matrix, i.e. finds such similarity transformation of the original
matrix A: A = T * bA * T^{-1}, where norms of columns of bA and of rows of bA
are as close as possible. It is usually used as a preprocessing step in
eigenvalue calculation routine. It is useful als... |
Balances State - Space model for more numerical stability | def balance_ss_model(F,L,Qc,H,Pinf,P0,dF=None,dQc=None,dPinf=None,dP0=None):
"""
Balances State-Space model for more numerical stability
This is based on the following:
dx/dt = F x + L w
y = H x
Let T z = x, which gives
dz/dt = inv(T) F T z + inv(T) L w
y = H T z
"""... |
Function returns the inverse square root of R matrix on step k. | def R_isrk(self, k):
"""
Function returns the inverse square root of R matrix on step k.
"""
ind = int(self.index[self.R_time_var_index, k])
R = self.R[:, :, ind]
if (R.shape[0] == 1): # 1-D case handle simplier. No storage
# of the result, just compute it e... |
function ( k m P ) return Jacobian of measurement function it is passed into p_h. k ( iteration number ) starts at 0 m: point where Jacobian is evaluated P: parameter for Jacobian usually covariance matrix. | def Hk(self, k, m_pred, P_pred): # returns state iteration matrix
"""
function (k, m, P) return Jacobian of measurement function, it is
passed into p_h.
k (iteration number), starts at 0
m: point where Jacobian is evaluated
P: parameter for Jacobian, usua... |
function ( k ). Returns noise matrix of dynamic model on iteration k. k ( iteration number ). starts at 0 | def Qk(self, k):
"""
function (k). Returns noise matrix of dynamic model on iteration k.
k (iteration number). starts at 0
"""
return self.Q[:, :, self.index[self.Q_time_var_index, k]] |
function ( k ). Returns the square root of noise matrix of dynamic model on iteration k. k ( iteration number ). starts at 0 | def Q_srk(self, k):
"""
function (k). Returns the square root of noise matrix of dynamic model
on iteration k.
k (iteration number). starts at 0
This function is implemented to use SVD prediction step.
"""
ind = self.index[self.Q_time_var_index,... |
function ( k m P ) return Jacobian of measurement function it is passed into p_h. k ( iteration number ) starts at 0 m: point where Jacobian is evaluated P: parameter for Jacobian usually covariance matrix. | def Ak(self, k, m_pred, P_pred): # returns state iteration matrix
"""
function (k, m, P) return Jacobian of measurement function, it is
passed into p_h.
k (iteration number), starts at 0
m: point where Jacobian is evaluated
P: parameter for Jacobian, usua... |
Static function returns the column - wise shape for for an input shape. | def _reshape_input_data(shape, desired_dim=3):
"""
Static function returns the column-wise shape for for an input shape.
Input:
--------------
shape: tuple
Shape of an input array, so that it is always a column.
desired_dim: int
d... |
This function implements the basic Kalman Filter algorithm These notations for the State - Space model are assumed: x_ { k } = A_ { k } * x_ { k - 1 } + q_ { k - 1 } ; q_ { k - 1 } ~ N ( 0 Q_ { k - 1 } ) y_ { k } = H_ { k } * x_ { k } + r_ { k } ; r_ { k - 1 } ~ N ( 0 R_ { k } ) | def kalman_filter(cls, p_A, p_Q, p_H, p_R, Y, index=None, m_init=None,
P_init=None, p_kalman_filter_type='regular',
calc_log_likelihood=False,
calc_grad_log_likelihood=False, grad_params_no=None,
grad_calc_params=None):
"""
... |
Extended Kalman Filter | def extended_kalman_filter(cls,p_state_dim, p_a, p_f_A, p_f_Q, p_h, p_f_H, p_f_R, Y, m_init=None,
P_init=None,calc_log_likelihood=False):
"""
Extended Kalman Filter
Input:
-----------------
p_state_dim: integer
p_a: if None - the function fro... |
General nonlinear filtering algorithm for inference in the state - space model: | def _kalman_algorithm_raw(cls,state_dim, p_dynamic_callables, p_measurement_callables, Y, m_init,
P_init, p_kalman_filter_type='regular',
calc_log_likelihood=False,
calc_grad_log_likelihood=False, grad_params_no=None,
... |
Desctrete prediction function | def _kalman_prediction_step(k, p_m , p_P, p_dyn_model_callable, calc_grad_log_likelihood=False,
p_dm = None, p_dP = None):
"""
Desctrete prediction function
Input:
k:int
Iteration No. Starts at 0. Total number of iterations equal to th... |
Desctrete prediction function | def _kalman_prediction_step_SVD(k, p_m , p_P, p_dyn_model_callable, calc_grad_log_likelihood=False,
p_dm = None, p_dP = None):
"""
Desctrete prediction function
Input:
k:int
Iteration No. Starts at 0. Total number of iterations equal t... |
Input: | def _kalman_update_step(k, p_m , p_P, p_meas_model_callable, measurement, calc_log_likelihood= False,
calc_grad_log_likelihood=False, p_dm = None, p_dP = None):
"""
Input:
k: int
Iteration No. Starts at 0. Total number of iterations equal to the
... |
Input: | def _kalman_update_step_SVD(k, p_m , p_P, p_meas_model_callable, measurement, calc_log_likelihood= False,
calc_grad_log_likelihood=False, p_dm = None, p_dP = None):
"""
Input:
k: int
Iteration No. Starts at 0. Total number of iterations equal to the
... |
Rauch–Tung–Striebel ( RTS ) update step | def _rts_smoother_update_step(k, p_m , p_P, p_m_pred, p_P_pred, p_m_prev_step,
p_P_prev_step, p_dynamic_callables):
"""
Rauch–Tung–Striebel(RTS) update step
Input:
-----------------------------
k: int
Iteration No. Starts at 0. Tot... |
This function implements Rauch–Tung–Striebel ( RTS ) smoother algorithm based on the results of kalman_filter_raw. These notations are the same: x_ { k } = A_ { k } * x_ { k - 1 } + q_ { k - 1 } ; q_ { k - 1 } ~ N ( 0 Q_ { k - 1 } ) y_ { k } = H_ { k } * x_ { k } + r_ { k } ; r_ { k - 1 } ~ N ( 0 R_ { k } ) | def rts_smoother(cls,state_dim, p_dynamic_callables, filter_means,
filter_covars):
"""
This function implements Rauch–Tung–Striebel(RTS) smoother algorithm
based on the results of kalman_filter_raw.
These notations are the same:
x_{k} = A_{k} * x_{k... |
Gradient computation with the EM algorithm. | def _EM_gradient(A,Q,H,R,m_init,P_init,measurements, M, P, G, dA, dQ, dH, dR, dm_init, dP_init):
"""
Gradient computation with the EM algorithm.
Input:
-----------------
M: Means from the smoother
P: Variances from the smoother
G: Gains? from the smoother
... |
Veryfy that on exit the matrix has appropriate shape for the KF algorithm. | def _check_SS_matrix(p_M, state_dim, measurement_dim, which='A'):
"""
Veryfy that on exit the matrix has appropriate shape for the KF algorithm.
Input:
p_M: matrix
As it is given for the user
state_dim: int
State dimensioanlity
... |
Function checks ( mostly check dimensions ) matrices for marginal likelihood gradient parameters calculation. It check dA dQ matrices. | def _check_grad_state_matrices(dM, state_dim, grad_params_no, which = 'dA'):
"""
Function checks (mostly check dimensions) matrices for marginal likelihood
gradient parameters calculation. It check dA, dQ matrices.
Input:
-------------
dM: None, scaler or 3D matrix
... |
Function checks ( mostly check dimensions ) matrices for marginal likelihood gradient parameters calculation. It check dH dR matrices. | def _check_grad_measurement_matrices(dM, state_dim, grad_params_no, measurement_dim, which = 'dH'):
"""
Function checks (mostly check dimensions) matrices for marginal likelihood
gradient parameters calculation. It check dH, dR matrices.
Input:
-------------
dM: None... |
This function implements the continuous - discrete Kalman Filter algorithm These notations for the State - Space model are assumed: d/ dt x ( t ) = F * x ( t ) + L * w ( t ) ; w ( t ) ~ N ( 0 Qc ) y_ { k } = H_ { k } * x_ { k } + r_ { k } ; r_ { k - 1 } ~ N ( 0 R_ { k } ) | def cont_discr_kalman_filter(cls, F, L, Qc, p_H, p_R, P_inf, X, Y, index = None,
m_init=None, P_init=None,
p_kalman_filter_type='regular',
calc_log_likelihood=False,
calc_grad_log_likeliho... |
Function return the object which is used in Kalman filter and/ or smoother to obtain matrices A Q and their derivatives for discrete model from the continuous model. | def _cont_to_discrete_object(cls, X, F, L, Qc, compute_derivatives=False,
grad_params_no=None,
P_inf=None, dP_inf=None, dF = None, dQc=None,
dt0=None):
"""
Function return the object which is used in Kalma... |
Linear Time - Invariant Stochastic Differential Equation ( LTI SDE ): | def lti_sde_to_descrete(F,L,Qc,dt,compute_derivatives=False,
grad_params_no=None, P_inf=None,
dP_inf=None, dF = None, dQc=None):
"""
Linear Time-Invariant Stochastic Differential Equation (LTI SDE):
dx(t) = F x(t) dt + L d \beta ,wher... |
Computes the network preactivations i. e. the results of all intermediate linear layers before applying the activation function on them: param X: input data: return: list of preactivations [ X XW + b f ( XW + b ) W + b... ] | def _f_preactivations(self, X):
"""Computes the network preactivations, i.e. the results of all intermediate linear layers before applying the
activation function on them
:param X: input data
:return: list of preactivations [X, XW+b, f(XW+b)W+b, ...]
"""
preactivations_l... |
Helper function that fixes all parameters | def fix_parameters(self):
"""Helper function that fixes all parameters"""
for W, b in zip(self.W_list, self.b_list):
W.fix()
b.fix() |
Helper function that unfixes all parameters | def unfix_parameters(self):
"""Helper function that unfixes all parameters"""
for W, b in zip(self.W_list, self.b_list):
W.unfix()
b.unfix() |
A decorator that allows catching numpy invalid operations as exceptions ( the default behaviour is raising warnings ). | def numpy_invalid_op_as_exception(func):
"""
A decorator that allows catching numpy invalid operations
as exceptions (the default behaviour is raising warnings).
"""
def func_wrapper(*args, **kwargs):
np.seterr(invalid='raise')
result = func(*args, **kwargs)
np.seterr(invalid... |
Function computes the derivative of Kronecker product A * B ( or Kronecker sum A + B ). | def dkron(A,dA,B,dB, operation='prod'):
"""
Function computes the derivative of Kronecker product A*B
(or Kronecker sum A+B).
Input:
-----------------------
A: 2D matrix
Some matrix
dA: 3D (or 2D matrix)
Derivarives of A
B: 2D matrix
Some matrix
dB: 3D (or 2... |
Convert the object into a json serializable dictionary. | def to_dict(self):
"""
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object
"""
input_dict = su... |
Update gradient in the order in which parameters are represented in the kernel | def sde_update_gradient_full(self, gradients):
"""
Update gradient in the order in which parameters are represented in the
kernel
"""
part_start_param_index = 0
for p in self.parts:
if not p.is_fixed:
part_param_num = len(p.param_array) # numbe... |
Convert the object into a json serializable dictionary. | def to_dict(self):
"""
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object
"""
input_dict = su... |
Compute the covariance matrix between X and X2. | def K(self, X, X2=None):
"""Compute the covariance matrix between X and X2."""
if X2 is None:
X2 = X
base = np.pi * (X[:, None, :] - X2[None, :, :]) / self.period
exp_dist = np.exp( -0.5* np.sum( np.square( np.sin( base ) / self.lengthscale ), axis = -1 ) )
return ... |
Compute the diagonal of the covariance matrix associated to X. | def Kdiag(self, X):
"""Compute the diagonal of the covariance matrix associated to X."""
ret = np.empty(X.shape[0])
ret[:] = self.variance
return ret |
derivative of the covariance matrix with respect to the parameters. | def update_gradients_full(self, dL_dK, X, X2=None):
"""derivative of the covariance matrix with respect to the parameters."""
if X2 is None:
X2 = X
base = np.pi * (X[:, None, :] - X2[None, :, :]) / self.period
sin_base = np.sin( base )
exp_dist = np.exp( -0.5* np.su... |
derivative of the diagonal of the covariance matrix with respect to the parameters. | def update_gradients_diag(self, dL_dKdiag, X):
"""derivative of the diagonal of the covariance matrix with respect to the parameters."""
self.variance.gradient = np.sum(dL_dKdiag)
self.period.gradient = 0
self.lengthscale.gradient = 0 |
Plot the geometry of a shapefile | def plot(shape_records,facecolor='w',edgecolor='k',linewidths=.5, ax=None,xlims=None,ylims=None):
"""
Plot the geometry of a shapefile
:param shape_records: geometry and attributes list
:type shape_records: ShapeRecord object (output of a shapeRecords() method)
:param facecolor: color to be used to... |
Return the geometry and attributes of a shapefile whose fields match a regular expression given | def string_match(sf,regex,field=2):
"""
Return the geometry and attributes of a shapefile whose fields match a regular expression given
:param sf: shapefile
:type sf: shapefile object
:regex: regular expression to match
:type regex: string
:field: field number to be matched with the regex
... |
Return the geometry and attributes of a shapefile that lie within ( or intersect ) a bounding box | def bbox_match(sf,bbox,inside_only=True):
"""
Return the geometry and attributes of a shapefile that lie within (or intersect) a bounding box
:param sf: shapefile
:type sf: shapefile object
:param bbox: bounding box
:type bbox: list of floats [x_min,y_min,x_max,y_max]
:inside_only: True if ... |
Plot the geometry of a shapefile within a bbox | def plot_bbox(sf,bbox,inside_only=True):
"""
Plot the geometry of a shapefile within a bbox
:param sf: shapefile
:type sf: shapefile object
:param bbox: bounding box
:type bbox: list of floats [x_min,y_min,x_max,y_max]
:inside_only: True if the objects returned are those that lie within the... |
Plot the geometry of a shapefile whose fields match a regular expression given | def plot_string_match(sf,regex,field,**kwargs):
"""
Plot the geometry of a shapefile whose fields match a regular expression given
:param sf: shapefile
:type sf: shapefile object
:regex: regular expression to match
:type regex: string
:field: field number to be matched with the regex
:t... |
Use bbox as xlim and ylim in ax | def apply_bbox(sf,ax):
"""
Use bbox as xlim and ylim in ax
"""
limits = sf.bbox
xlim = limits[0],limits[2]
ylim = limits[1],limits[3]
ax.set_xlim(xlim)
ax.set_ylim(ylim) |
Notice that we update the warping function gradients here. | def parameters_changed(self):
"""
Notice that we update the warping function gradients here.
"""
self.Y_normalized[:] = self.transform_data()
super(WarpedGP, self).parameters_changed()
Kiy = self.posterior.woodbury_vector.flatten()
self.warping_function.update_gra... |
Notice we add the jacobian of the warping function here. | def log_likelihood(self):
"""
Notice we add the jacobian of the warping function here.
"""
ll = GP.log_likelihood(self)
jacobian = self.warping_function.fgrad_y(self.Y_untransformed)
return ll + np.log(jacobian).sum() |
Calculate the warped mean by using Gauss - Hermite quadrature. | def _get_warped_mean(self, mean, std, pred_init=None, deg_gauss_hermite=20):
"""
Calculate the warped mean by using Gauss-Hermite quadrature.
"""
gh_samples, gh_weights = np.polynomial.hermite.hermgauss(deg_gauss_hermite)
gh_samples = gh_samples[:, None]
gh_weights = gh_w... |
Calculate the warped variance by using Gauss - Hermite quadrature. | def _get_warped_variance(self, mean, std, pred_init=None, deg_gauss_hermite=20):
"""
Calculate the warped variance by using Gauss-Hermite quadrature.
"""
gh_samples, gh_weights = np.polynomial.hermite.hermgauss(deg_gauss_hermite)
gh_samples = gh_samples[:, None]
gh_weight... |
Prediction results depend on: - The value of the self. predict_in_warped_space flag - The median flag passed as argument The likelihood keyword is never used it is just to follow the plotting API. | def predict(self, Xnew, kern=None, pred_init=None, Y_metadata=None,
median=False, deg_gauss_hermite=20, likelihood=None):
"""
Prediction results depend on:
- The value of the self.predict_in_warped_space flag
- The median flag passed as argument
The likelihood key... |
Get the predictive quantiles around the prediction at X | def predict_quantiles(self, X, quantiles=(2.5, 97.5), Y_metadata=None, likelihood=None, kern=None):
"""
Get the predictive quantiles around the prediction at X
:param X: The points at which to make a prediction
:type X: np.ndarray (Xnew x self.input_dim)
:param quantiles: tuple ... |
Calculation of the log predictive density. Notice we add the jacobian of the warping function here. | def log_predictive_density(self, x_test, y_test, Y_metadata=None):
"""
Calculation of the log predictive density. Notice we add
the jacobian of the warping function here.
.. math:
p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*})
:param x_test: test locatio... |
Update gradient in the order in which parameters are represented in the kernel | def sde_update_gradient_full(self, gradients):
"""
Update gradient in the order in which parameters are represented in the
kernel
"""
self.variance.gradient = gradients[0]
self.lengthscale.gradient = gradients[1] |
Return the state space representation of the covariance. | def sde(self):
"""
Return the state space representation of the covariance.
"""
variance = float(self.variance.values)
lengthscale = float(self.lengthscale.values)
lamda = np.sqrt(5.0)/lengthscale
kappa = 5.0/3.0*variance/lengthscale**2
... |
Sample the ( unfixed ) model parameters.: param num_samples: the number of samples to draw ( 1000 by default ): type num_samples: int: param hmc_iters: the number of leap - frog iterations ( 20 by default ): type hmc_iters: int: return: the list of parameters samples with the size N x P ( N - the number of samples P - ... | def sample(self, num_samples=1000, hmc_iters=20):
"""
Sample the (unfixed) model parameters.
:param num_samples: the number of samples to draw (1000 by default)
:type num_samples: int
:param hmc_iters: the number of leap-frog iterations (20 by default)
:type hmc_... |
Method that is called upon any changes to: class: ~GPy. core. parameterization. param. Param variables within the model. In particular in the GP class this method reperforms inference recalculating the posterior and log marginal likelihood and gradients of the model | def parameters_changed(self):
"""
Method that is called upon any changes to :class:`~GPy.core.parameterization.param.Param` variables within the model.
In particular in the GP class this method reperforms inference, recalculating the posterior and log marginal likelihood and gradients of the mod... |
Make a prediction for the latent function values | def _raw_predict(self, Xnew, full_cov=False, kern=None):
"""
Make a prediction for the latent function values
"""
if kern is None:
kern = self.kern
# compute mean predictions
Kmn = kern.K(Xnew, self.X)
alpha_kron = self.posterior.alpha
mu = np... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.