INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 which match names in the list of names in filtering will be used f...
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...
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 n...
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...
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 of two variables!) :param plot_limits: the range over which to plot the kernel :type plot_limits: Either (xmin, xmax) for 1D or (xmin, xmax, ymin, ymax) / ((xmin, xmax), (y...
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...
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. :data_set: A data set from the utils.datasets director. :length_scales: a list of length scales to explore for the contour plot. :log_SNRs: a list of base 10 logarithm signal to no...
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. :param X1new: The points at which to make a prediction :type X1new: np.ndarray, Nnew x self.input_dim1 :param X2new: The points at which to make ...
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...
Figure out the data, free_dims and create an Xgrid for the prediction. This is only implemented for two dimensions for now!
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...
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 anything in here lightly!!!
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...
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. This is used for updated kwargs from the default dicts.
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 If (X, X_variance, Y) is given, this just returns. :returns: (X, X_variance, Y)
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) 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.
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. :param array-like labels: a label for each data point (row) of the inputs :param (int, int) which_indices: which input dimensions to plot against each other :param bool legend: whether to plot the legend on the figure :param plot_limits: the plot limits for the ...
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. :param [int] which_indices: which input dimensions to plot against each other :param bool legend: whether to plot the legend on the figure :param plot_limits: the plot limits for the plot :type plot_limits: (xmin, xmax, ymin, ymax) or ((xmin, xmax), (ymin, ym...
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. :param array-like labels: a label for each data point (row) of the inputs :param (int, int) which_indices: which input dimensions to plot against each other :param int resolution: the resolution at whi...
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. :param array-like labels: a label for each data point (row) of the inputs :param (int, int) which_indices: which input dimension...
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. :param array-like labels: a label for each data point (row) of the inputs :param (int, int) which_indices: which input dimension...
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. See ...
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 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
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). 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, 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 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.
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. Input: -------------- shape: tuple Shape of an input array, so that it is always a column. desired_dim: int desired shape of output. For Y data it should be 3 (...
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}) Returns estimated filter distributi...
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 Input: ----------------- p_state_dim: integer p_a: if None - the function from the linear model is assumed. No non- linearity in the dynamic is assumed. function (k, x_{k-1}, A_{k}). Dynamic function. k: (iteration number)...
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: x_{k} = f_a(k, x_{k-1}, A_{k}) + q_{k-1}; q_{k-1} ~ N(0, Q_{k-1}) y_{k} = f_h(k, x_{k}, H_{k}) + r_{k}; r_{k-1} ~ N(0, R_{k}) Returns estimated filter distributions x_{k} ~ N(m_{k}, P(k)) ...
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 Input: k:int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. p_m: matrix of size (state_dim, time_series_no) Mean value from the previous step. For "multiple time se...
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 Input: k:int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. p_m: matrix of size (state_dim, time_series_no) Mean value from the previous step. For "multiple time se...
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: k: int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. m_P: matrix of size (state_dim, time_series_no) Mean value from the previous step. For "multiple time series mode" it is matrix, second dime...
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: k: int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. m_P: matrix of size (state_dim, time_series_no) Mean value from the previous step. For "multiple time series mode" it is matrix, second dime...
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 ...
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...
Rauch–Tung–Striebel(RTS) update step Input: ----------------------------- k: int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. p_m: matrix of size (state_dim, time_series_no) Filter mean on step k ...
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...
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 measurement_dim: int Measurement dimensionality which: st...
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 ...
Gradient computation with the EM algorithm. Input: ----------------- M: Means from the smoother P: Variances from the smoother G: Gains? from the smoother
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 ...
Function checks (mostly check dimensions) matrices for marginal likelihood gradient parameters calculation. It check dA, dQ matrices. Input: ------------- dM: None, scaler or 3D matrix It is supposed to be (state_dim,state_dim,grad_params_no) matrix. ...
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. Input: ------------- dM: None, scaler or 3D matrix It is supposed to be (measurement_dim ,state_dim,grad_params_no) f...
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}) Returns estimated filter dist...
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. There are 2 objects AQcompute_once and AQcompute_batch and the function returs the appropriate one based on the number of...
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): dx(t) = F x(t) dt + L d \beta ,where x(t): (vector) stochastic process \beta: (vector) Brownian motion process F, L: (time invariant) matrices of corresponding dimensions Qc: ...
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). Input: ----------------------- A: 2D matrix Some matrix dA: 3D (or 2D matrix) Derivarives of A B: 2D matrix Some matrix dB: 3D (or 2D matrix) Derivarives of B operation: s...
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. 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
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. 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
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 :param shape_records: geometry and attributes list :type shape_records: ShapeRecord object (output of a shapeRecords() method) :param facecolor: color to be used to fill in polygons :param edgecolor: color to be used for lines :param ax: axes to plot on. :type a...
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 :param sf: shapefile :type sf: shapefile object :regex: regular expression to match :type regex: string :field: field number to be matched with the regex :type field: integer
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 :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 bbo...
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 :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 bbox and False if the objects returned are any that ...
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 :param sf: shapefile :type sf: shapefile object :regex: regular expression to match :type regex: string :field: field number to be matched with the regex :type field: integer
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 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()
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...
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 :param X: The points at which to make a prediction :type X: np.ndarray (Xnew x self.input_dim) :param quantiles: tuple of quantiles, default is (2.5, 97.5) which is the 95% interval :type quantiles: tuple :returns: list of ...
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. .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param x_test: test locations (x_{*}) :type x_test: (Nx1) array :param y_test: test observations (...
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 si...
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 .. warning:: This method i...
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...
Return the state space representation of the covariance.
def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variances.values) # this is initial variancve in Bayesian linear regression t0 = float(self.t0) F = np.array( ((0,1.0),(0,0) )) L = np.array...
Compute the covariance matrix between X and X2.
def K(self, X, X2=None): # model : -a d^2y/dx^2 + b dy/dt + c * y = U # kernel Kyy rbf spatiol temporal # vyt Y temporal variance vyx Y spatiol variance lyt Y temporal lengthscale lyx Y spatiol lengthscale # kernel Kuu doper( doper(Kyy)) # a b c lyt lyx vyx*vyt "...
Compute the diagonal of the covariance matrix associated to X.
def Kdiag(self, X): """Compute the diagonal of the covariance matrix associated to X.""" vyt = self.variance_Yt vyx = self.variance_Yx lyt = 1./(2*self.lengthscale_Yt) lyx = 1./(2*self.lengthscale_Yx) a = self.a b = self.b c = self.c ## dk^2/dtd...
derivative of the covariance matrix with respect to the parameters.
def update_gradients_full(self, dL_dK, X, X2=None): #def dK_dtheta(self, dL_dK, X, X2, target): """derivative of the covariance matrix with respect to the parameters.""" X,slices = X[:,:-1],index_to_slices(X[:,-1]) if X2 is None: X2,slices2 = X,slices K = np.zeros((X....
Get the gradients of the posterior distribution of X in its specific form.
def get_X_gradients(self, X): """Get the gradients of the posterior distribution of X in its specific form.""" return X.mean.gradient, X.variance.gradient, X.binary_prob.gradient
Sample the loading matrix if the kernel is linear.
def sample_W(self, nSamples, raw_samples=False): """ Sample the loading matrix if the kernel is linear. """ assert isinstance(self.kern, kern.Linear) from ..util.linalg import pdinv N, D = self.Y.shape Q = self.X.shape[1] noise_var = self.likelihood.varian...