code
stringlengths
1
18.2k
def find_duplicate_schedule_items(all_items): """Find talks / pages assigned to mulitple schedule items""" duplicates = [] seen_talks = {} for item in all_items: if item.talk and item.talk in seen_talks: duplicates.append(item) if seen_talks[item.talk] not in duplicates: duplicates.append(seen_talks[item.talk]) else: s...
cases. This may be revisited later return duplicates
def find_clashes(all_items): """Find schedule items which clash (common slot and venue)""" clashes = {} seen_venue_slots = {} for item in all_items: for slot in item.slots.all(): pos = (item.venue, slot) if pos in seen_venue_slots: if seen_venue_slots[pos] not in clashes: clashes[pos] = [seen_venue_slots[pos]] clashes[...
def find_invalid_venues(all_items): """Find venues assigned slots that aren't on the allowed list of days.""" venues = {} for item in all_items: valid = False item_days = list(item.venue.days.all()) for slot in item.slots.all(): for day in item_days: if day == slot.get_day(): valid = True break if not valid: venues.set...
def check_schedule(): """Helper routine to easily test if the schedule is valid""" all_items = prefetch_schedule_items() for validator, _type, _msg in SCHEDULE_ITEM_VALIDATORS: if validator(all_items): return False all_slots = prefetch_slots() for validator, _type, _msg in SLOT_VALIDATORS: if validator(all_slots): retu...
def validate_schedule(): """Helper routine to report issues with the schedule""" all_items = prefetch_schedule_items() errors = [] for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS: if validator(all_items): errors.append(msg) all_slots = prefetch_slots() for validator, _type, msg in SLOT_VALIDATORS: if validator(al...
def get_form(self, request, obj=None, **kwargs): """Change the form depending on whether we're adding or editing the slot.""" if obj is None: # Adding a new Slot kwargs['form'] = SlotAdminAddForm return super(SlotAdmin, self).get_form(request, obj, **kwargs)
def get_cached_menus(): """Return the menus from the cache or generate them if needed.""" items = cache.get(CACHE_KEY) if items is None: menu = generate_menu() cache.set(CACHE_KEY, menu.items) else: menu = Menu(items) return menu
def maybe_obj(str_or_obj): """If argument is not a string, return it. Otherwise import the dotted name and return that. """ if not isinstance(str_or_obj, six.string_types): return str_or_obj parts = str_or_obj.split(".") mod, modname = None, None for p in parts: modname = p if modname is None else "%s.%s" % (modname, p...
for p in parts[1:]: obj = getattr(obj, p) return obj
def generate_menu(): """Generate a new list of menus.""" root_menu = Menu(list(copy.deepcopy(settings.WAFER_MENUS))) for dynamic_menu_func in settings.WAFER_DYNAMIC_MENUS: dynamic_menu_func = maybe_obj(dynamic_menu_func) dynamic_menu_func(root_menu) return root_menu
def lock(self): ''' Try to get locked the file - the function will wait until the file is unlocked if 'wait' was defined as locktype - the funciton will raise AlreadyLocked exception if 'lock' was defined as locktype ''' # Open file self.__fd = open(self.__lockfile, "w") # Get it locked if self.__locktype == "wait": # ...
elif self.__locktype == "lock": # Try to get the locker if can not raise an exception try: fcntl.flock(self.__fd.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB) except IOError: raise AlreadyLocked("File is already locked")
def _make_handler(state_token, done_function): ''' Makes a a handler class to use inside the basic python HTTP server. state_token is the expected state token. done_function is a function that is called, with the code passed to it. ''' class LocalServerHandler(BaseHTTPServer.BaseHTTPRequestHandler): def error_response(...
parsed.path != '/callback': self.error_response( 'We encountered a problem with your request.') return params = urlparse.parse_qs(parsed.query) if params['state'] != [state_token]: self.error_response( 'Attack detected: state tokens did not match!') return if len(params['code']) != 1: self.error_response('Wrong number ...
your terminal. Thanks!") done_function(params['code'][0]) return LocalServerHandler
def configuration(): 'Loads configuration from the file system.' defaults = ''' [oauth2] hostname = localhost port = 9876 api_endpoint = https://api.coursera.org auth_endpoint = https://accounts.coursera.org/oauth2/v1/auth token_endpoint = https://accounts.coursera.org/oauth2/v1/token verify_tls = True token_cache_base...
]) return cfg
def _load_token_cache(self): 'Reads the local fs cache for pre-authorized access tokens' try: logging.debug('About to read from local file cache file %s', self.token_cache_file) with open(self.token_cache_file, 'rb') as f: fs_cached = cPickle.load(f) if self._check_token_cache_type(fs_cached): logging.debug('Loaded fro...
None except: logging.info( 'Encountered exception loading from the file system.', exc_info=True) return None
def _save_token_cache(self, new_cache): 'Write out to the filesystem a cache of the OAuth2 information.' logging.debug('Looking to write to local authentication cache...') if not self._check_token_cache_type(new_cache): logging.error('Attempt to save a bad value: %s', new_cache) return try: logging.debug('About to writ...
OAuth2 secrets on the file ' 'system.')
def _check_token_cache_type(self, cache_value): ''' Checks the cache_value for appropriate type correctness. Pass strict=True for strict validation to ensure the latest types are being written. Returns true is correct type, False otherwise. ''' def check_string_value(name): return ( isinstance(cache_value[name], str) o...
cache_value and check_string_value('token') and isinstance(cache_value['expires'], float) and check_refresh_token() )
def _authorize_new_tokens(self): ''' Stands up a new localhost http server and retrieves new OAuth2 access tokens from the Coursera OAuth2 server. ''' logging.info('About to request new OAuth2 tokens from Coursera.') # Attempt to request new tokens from Coursera via the browser. state_token = uuid.uuid4().hex authoriza...
# OS X -- leverage the 'open' command present on all modern macs sys.stdout.write( 'Mac OS X detected; attempting to auto-open the url ' 'in your default browser...\n') try: subprocess.check_call(['open', authorization_url]) except: logging.exception('Could not call `open %(url)s`.', url=authorization_url) if self.loca...
_make_handler(state_token, code_holder)) while not code_holder.has_code(): local_server.handle_request() coursera_code = code_holder.code else: coursera_code = raw_input('Please enter the code from Coursera: ') form_data = { 'code': coursera_code, 'client_id': self.client_id, 'client_secret': self.client_secret, 'redir...
def _exchange_refresh_tokens(self): 'Exchanges a refresh token for an access token' if self.token_cache is not None and 'refresh' in self.token_cache: # Attempt to use the refresh token to get a new access token. refresh_form = { 'grant_type': 'refresh_token', 'refresh_token': self.token_cache['refresh'], 'client_id': ...
None
def foreignkey(element, exceptions): ''' function to determine if each select field needs a create button or not ''' label = element.field.__dict__['label'] try: label = unicode(label) except NameError: pass if (not label) or (label in exceptions): return False else: return "_queryset" in element.field.__dict__
def deserialize_by_field(value, field): """ Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them """ if isinstance(field, forms.DateTimeField): value = parse_datetime(value) elif isinstance(field, forms.DateField): value = parse_date(value) elif isinstance(fiel...
def hyperprior(self): """Combined hyperprior for the kernel, noise kernel and (if present) mean function. """ hp = self.k.hyperprior * self.noise_k.hyperprior if self.mu is not None: hp *= self.mu.hyperprior return hp
def fixed_params(self): """Combined fixed hyperparameter flags for the kernel, noise kernel and (if present) mean function. """ fp = CombinedBounds(self.k.fixed_params, self.noise_k.fixed_params) if self.mu is not None: fp = CombinedBounds(fp, self.mu.fixed_params) return fp
def params(self): """Combined hyperparameters for the kernel, noise kernel and (if present) mean function. """ p = CombinedBounds(self.k.params, self.noise_k.params) if self.mu is not None: p = CombinedBounds(p, self.mu.params) return p
def param_names(self): """Combined names for the hyperparameters for the kernel, noise kernel and (if present) mean function. """ pn = CombinedBounds(self.k.param_names, self.noise_k.param_names) if self.mu is not None: pn = CombinedBounds(pn, self.mu.param_names) return pn
def free_params(self): """Combined free hyperparameters for the kernel, noise kernel and (if present) mean function. """ p = CombinedBounds(self.k.free_params, self.noise_k.free_params) if self.mu is not None: p = CombinedBounds(p, self.mu.free_params) return p
def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) self.K_up_to_date = False self.k.free_params = value[:self.k.num_free_params] self.noise_k.free_params = value[self.k.num_free_params:self.k.num_free_params + self.noise_k.num_...
def free_param_bounds(self): """Combined free hyperparameter bounds for the kernel, noise kernel and (if present) mean function. """ fpb = CombinedBounds(self.k.free_param_bounds, self.noise_k.free_param_bounds) if self.mu is not None: fpb = CombinedBounds(fpb, self.mu.free_param_bounds) return fpb
def free_param_names(self): """Combined free hyperparameter names for the kernel, noise kernel and (if present) mean function. """ p = CombinedBounds(self.k.free_param_names, self.noise_k.free_param_names) if self.mu is not None: p = CombinedBounds(p, self.mu.free_param_names) return p
def add_data(self, X, y, err_y=0, n=0, T=None): """Add data to the training data set of the GaussianProcess instance. Parameters ---------- X : array, (`M`, `D`) `M` input values of dimension `D`. y : array, (`M`,) `M` target values. err_y : array, (`M`,) or scalar float, optional Non-negative values only. Error given ...
the data set is taken to be homoscedastic (constant error). Otherwise, the length of `err_y` must equal the length of `y`. Default value is 0 (noiseless observations). n : array, (`M`, `D`) or scalar float, optional Non-negative integer values only. Degree of derivative for each target. If `n` is a scalar it is taken t...
the length of n must equal the length of `y`. Default value is 0 (observation of target value). If non-integer values are passed, they will be silently rounded. T : array, (`M`, `N`), optional Linear transformation to get from latent variables to data in the argument `y`. When `T` is passed the argument `y` holds the t...
values of the transformed quantities, `T` is the transformation matrix and `Y(X)` is the underlying (untransformed) values of the function to be fit that enter into the transformation. When `T` is `M`-by-`N` and `y` has `M` elements, `X` and `n` will both be `N`-by-`D`. Default is None (no transformation). Raises -----...
`n`. """ # Verify y has only one non-trivial dimension: y = scipy.atleast_1d(scipy.asarray(y, dtype=float)) if len(y.shape) != 1: raise ValueError( "Training targets y must have only one dimension with length " "greater than one! Shape of y given is %s" % (y.shape,) ) # Handle scalar error or verify shape of array erro...
* scipy.ones_like(y, dtype=float) else: err_y = scipy.asarray(err_y, dtype=float) if err_y.shape != y.shape: raise ValueError( "When using array-like err_y, shape must match shape of y! " "Shape of err_y given is %s, shape of y given is %s." % (err_y.shape, y.shape) ) if (err_y < 0).any(): raise ValueError("All element...
X = scipy.atleast_2d(scipy.asarray(X, dtype=float)) # Correct single-dimension inputs: if self.num_dim == 1 and X.shape[0] == 1: X = X.T if T is None and X.shape != (len(y), self.num_dim): raise ValueError( "Shape of training inputs must be (len(y), k.num_dim)! X given " "has shape %s, shape of y is %s and num_dim=%d."...
of array derivative # orders matches shape of y: try: iter(n) except TypeError: n = n * scipy.ones_like(X, dtype=int) else: n = scipy.atleast_2d(scipy.asarray(n, dtype=int)) # Correct single-dimension inputs: if self.num_dim == 1 and n.shape[1] != 1: n = n.T if n.shape != X.shape: raise ValueError( "When using array-li...
given is %s and num_dim=%d." % (n.shape, y.shape, self.num_dim) ) if (n < 0).any(): raise ValueError("All elements of n must be non-negative integers!") # Handle transform: if T is None and self.T is not None: T = scipy.eye(len(y)) if T is not None: T = scipy.atleast_2d(scipy.asarray(T, dtype=float)) if T.ndim != 2: ra...
"T must have as many rows are there are elements in y!" ) if T.shape[1] != X.shape[0]: raise ValueError( "There must be as many columns in T as there are rows in X!" ) if self.T is None and self.X is not None: self.T = scipy.eye(len(self.y)) if self.T is None: self.T = T else: self.T = scipy.linalg.block_diag(self.T, T...
X else: self.X = scipy.vstack((self.X, X)) self.y = scipy.append(self.y, y) self.err_y = scipy.append(self.err_y, err_y) if self.n is None: self.n = n else: self.n = scipy.vstack((self.n, n)) self.K_up_to_date = False
def condense_duplicates(self): """Condense duplicate points using a transformation matrix. This is useful if you have multiple non-transformed points at the same location or multiple transformed points that use the same quadrature points. Won't change the GP if all of the rows of [X, n] are unique. Will create a transf...
will be arbitrary after this operation. If there are any transformed quantities (i.e., `self.T` is not None), it will also remove any quadrature points for which all of the weights are zero (even if all of the rows of [X, n] are unique). """ unique, inv = unique_rows( scipy.hstack((self.X, self.n)), return_inverse=True...
!= len(self.X): if self.T is None: self.T = scipy.eye(len(self.y)) new_T = scipy.zeros((len(self.y), unique.shape[0])) for j in xrange(0, len(inv)): new_T[:, inv[j]] += self.T[:, j] self.T = new_T self.n = unique[:, self.X.shape[1]:] self.X = unique[:, :self.X.shape[1]] # Also remove any points which don't enter into t...
is (n, n_Q), X is (n_Q, n_dim). good_cols = (self.T != 0.0).any(axis=0) self.T = self.T[:, good_cols] self.X = self.X[good_cols, :] self.n = self.n[good_cols, :]
def remove_outliers(self, thresh=3, **predict_kwargs): """Remove outliers from the GP with very simplistic outlier detection. Removes points that are more than `thresh` * `err_y` away from the GP mean. Note that this is only very rough in that it ignores the uncertainty in the GP mean at any given point. But you should...
anyways! Returns the values that were removed and a boolean array indicating where the removed points were. Parameters ---------- thresh : float, optional The threshold as a multiplier times `err_y`. Default is 3 (i.e., throw away all 3-sigma points). **predict_kwargs : optional kwargs All additional kwargs are passed ...
mean. (If you don't use MCMC, then the current value of the hyperparameters is used.) Returns ------- X_bad : array Input values of the bad points. y_bad : array Bad values. err_y_bad : array Uncertainties on the bad values. n_bad : array Derivative order of the bad values. bad_idxs : array Array of booleans with the o...
point was taken to be bad and subsequently removed. T_bad : array Transformation matrix of returned points. Only returned if :py:attr:`T` is not None for the instance. """ mean = self.predict( self.X, n=self.n, noise=False, return_std=False, output_transform=self.T, **predict_kwargs ) deltas = scipy.absolute(mean - sel...
so they can be returned: y_bad = self.y[bad_idxs] err_y_bad = self.err_y[bad_idxs] if self.T is not None: T_bad = self.T[bad_idxs, :] non_zero_cols = (T_bad != 0).all(axis=0) T_bad = T_bad[:, non_zero_cols] X_bad = self.X[non_zero_cols, :] n_bad = self.n[non_zero_cols, :] else: X_bad = self.X[bad_idxs, :] n_bad = self....
self.T = self.T[good_idxs, :] non_zero_cols = (self.T != 0).all(axis=0) self.T = self.T[:, non_zero_cols] self.X = self.X[non_zero_cols, :] self.n = self.n[non_zero_cols, :] self.y = self.y[good_idxs] self.err_y = self.err_y[good_idxs] self.K_up_to_date = False if self.T is None: return (X_bad, y_bad, err_y_bad, n_bad,...
def optimize_hyperparameters(self, method='SLSQP', opt_kwargs={}, verbose=False, random_starts=None, num_proc=None, max_tries=1): r"""Optimize the hyperparameters by maximizing the log-posterior. Leaves the :py:class:`GaussianProcess` instance in the optimized state. If :py:func:`scipy.optimize.minimize` is not availab...
log-posterior with respect to the hyperparameters to speed up the optimization. Note that only the squared exponential covariance kernel supports hyperparameter derivatives at present. Parameters ---------- method : str, optional The method to pass to :py:func:`scipy.optimize.minimize`. Refer to that function's docstri...
keywords to pass to :py:func:`scipy.optimize.minimize`. Refer to that function's docstring for valid options. Default is: {}. verbose : bool, optional Whether or not the output should be verbose. If True, the entire :py:class:`Result` object from :py:func:`scipy.optimize.minimize` is printed. If False, status informati...
to randomly perturb the starting guesses (distributed according to the hyperprior) in order to seek the global minimum. If None, then `num_proc` random starts will be performed. Default is None (do number of random starts equal to the number of processors allocated). Note that for `random_starts` != 0, the initial stat...
optional Number of processors to use with random starts. If 0, processing is not done in parallel. If None, all available processors are used. Default is None (use all available processors). max_tries : int, optional Number of times to run through the random start procedure if a solution is not found. Default is to onl...
None: opt_kwargs = {} else: opt_kwargs = dict(opt_kwargs) if 'method' in opt_kwargs: method = opt_kwargs['method'] if self.verbose: warnings.warn( "Key 'method' is present in opt_kwargs, will override option " "specified with method kwarg.", RuntimeWarning ) else: opt_kwargs['method'] = method if num_proc is None: num_...
= 1e16 param_ranges[scipy.where(scipy.isinf(param_ranges[:, 0])), 0] = -1e16 param_ranges[scipy.where(scipy.isinf(param_ranges[:, 1])), 1] = 1e16 if random_starts == 0: num_proc = 0 param_samples = [self.free_params[:]] else: if random_starts is None: random_starts = max(num_proc, 1) # Distribute random guesses accordi...
None while trial < max_tries and res_min is None: if trial >= 1: if self.verbose: warnings.warn( "No solutions found on trial %d, retrying random starts." % (trial - 1,), RuntimeWarning ) # Produce a new initial guess: if random_starts != 0: param_samples = self.hyperprior.random_draw(size=random_starts).T param_sample...
map try: res = map_fun( _OptimizeHyperparametersEval(self, opt_kwargs), param_samples ) finally: if num_proc > 1: pool.close() # Filter out the failed convergences: res = [r for r in res if r is not None] try: res_min = min(res, key=lambda r: r.fun) if scipy.isnan(res_min.fun) or scipy.isinf(res_min.fun): res_min = Non...
solution. Try changing the " "parameter bounds, picking a new initial guess or increasing the " "number of random starts." ) self.update_hyperparameters(res_min.x) if verbose: print("Got %d completed starts, optimal result is:" % (len(res),)) print(res_min) print("\nLL\t%.3g" % (-1 * res_min.fun)) for v, l in zip(res_m...
optimal. Status: %d, Message: '%s'. Try adjusting " "bounds, initial guesses or the number of random starts used." % ( method, res_min.status, res_min.message ), RuntimeWarning ) bounds = scipy.asarray(self.free_param_bounds) # Augment the bounds a little bit to catch things that are one step away: if ((res_min.x <= 1....
the bounds. Bounds are:\n" "%s\n, solution is:\n%s. Try adjusting bounds, initial guesses " "or the number of random starts used." % (str(bounds), str(res_min.x),) ) return (res_min, len(res))
def predict(self, Xstar, n=0, noise=False, return_std=True, return_cov=False, full_output=False, return_samples=False, num_samples=1, samp_kwargs={}, return_mean_func=False, use_MCMC=False, full_MC=False, rejection_func=None, ddof=1, output_transform=None, **kwargs): """Predict the mean and covariance at the inputs `Xs...
: array, (`M`, `D`) or scalar, non-negative int, optional Order of derivative to predict (0 is the base quantity). If `n` is scalar, the value is used for all points in `Xstar`. If non-integer values are passed, they will be silently rounded. Default is 0 (return base quantity). noise : bool, optional Whether or not no...
False (no noise in covariance). return_std : bool, optional Set to True to compute and return the standard deviation for the predictions, False to skip this step. Default is True (return tuple of (`mean`, `std`)). return_cov : bool, optional Set to True to compute and return the full covariance matrix for the predictio...
deviation and covariance matrix pre-computed, use the `full_output` keyword. full_output : bool, optional Set to True to return the full outputs in a dictionary with keys: ================= =========================================================================== mean mean of GP at requested points std standard devia...
is True) mean_func mean function of GP (only if `return_mean_func` is True) cov_func covariance of mean function of GP (zero if not using MCMC) std_func standard deviation of mean function of GP (zero if not using MCMC) mean_without_func mean of GP minus mean function of GP cov_without_func covariance matrix of just th...
portion of the fit ================= =========================================================================== return_samples : bool, optional Set to True to compute and return samples of the GP in addition to computing the mean. Only done if `full_output` is True. Default is False. num_samples : int, optional Number...
is the number of samples actually returned. Default is 1. samp_kwargs : dict, optional Additional keywords to pass to :py:meth:`draw_sample` if `return_samples` is True. Default is {}. return_mean_func : bool, optional Set to True to return the evaluation of the mean function in addition to computing the mean of the pr...
is False. use_MCMC : bool, optional Set to True to use :py:meth:`predict_MCMC` to evaluate the prediction marginalized over the hyperparameters. full_MC : bool, optional Set to True to compute the mean and covariance matrix using Monte Carlo sampling of the posterior. The samples will also be returned if full_output is...
conditional means and covariances can be computed. Default is False (do not use full sampling). rejection_func : callable, optional Any samples where this function evaluates False will be rejected, where it evaluates True they will be kept. Default is None (no rejection). Only has an effect if `full_MC` is True. ddof :...
covariance matrix when `full_MC` is True. Default is 1 (unbiased estimator). output_transform: array, (`L`, `M`), optional Matrix to use to transform the output vector of length `M` to one of length `L`. This can, for instance, be used to compute integrals. **kwargs : optional kwargs All additional kwargs are passed to...
mean. Only returned if `full_output` is False. std : array, (`M`,) Predicted standard deviation, only returned if `return_std` is True, `return_cov` is False and `full_output` is False. cov : array, (`M`, `M`) Predicted covariance matrix, only returned if `return_cov` is True and `full_output` is False. full_output : d...
returned if `full_output` is True. Raises ------ ValueError If `n` is not consistent with the shape of `Xstar` or is not entirely composed of non-negative integers. """ if use_MCMC: res = self.predict_MCMC( Xstar, n=n, noise=noise, return_std=return_std or full_output, return_cov=return_cov or full_output, return_sampl...
(res['mean'], res['cov']) elif return_std: return (res['mean'], res['std']) else: return res['mean'] else: # Process Xstar: Xstar = scipy.atleast_2d(scipy.asarray(Xstar, dtype=float)) # Handle 1d x case where array is passed in: if self.num_dim == 1 and Xstar.shape[0] == 1: Xstar = Xstar.T if Xstar.shape[1] != self.num...
% (Xstar.shape, self.num_dim) ) # Process T: if output_transform is not None: output_transform = scipy.atleast_2d(scipy.asarray(output_transform, dtype=float)) if output_transform.ndim != 2: raise ValueError( "output_transform must have exactly 2 dimensions! Shape " "of output_transform given is %s." % (output_transfor...
is %s, shape of Xstar is %s." % (output_transform.shape, Xstar.shape,) ) # Process n: try: iter(n) except TypeError: n = n * scipy.ones(Xstar.shape, dtype=int) else: n = scipy.atleast_2d(scipy.asarray(n, dtype=int)) if self.num_dim == 1 and n.shape[0] == 1: n = n.T if n.shape != Xstar.shape: raise ValueError( "When usi...
of Xstar given is %s." % (n.shape, Xstar.shape) ) if (n < 0).any(): raise ValueError("All elements of n must be non-negative integers!") self.compute_K_L_alpha_ll() Kstar = self.compute_Kij(self.X, Xstar, self.n, n) if noise: Kstar = Kstar + self.compute_Kij(self.X, Xstar, self.n, n, noise=True) if self.T is not None: ...
output_transform is not None: mean = output_transform.dot(mean) if return_mean_func and self.mu is not None: mean_func = output_transform.dot(mean_func) mean = mean.ravel() if return_mean_func and self.mu is not None: mean_func = mean_func.ravel() if return_std or return_cov or full_output or full_MC: v = scipy.linalg....
v.T.dot(v) if output_transform is not None: covariance = output_transform.dot(covariance.dot(output_transform.T)) if return_samples or full_MC: samps = self.draw_sample( Xstar, n=n, num_samp=num_samples, mean=mean, cov=covariance, **samp_kwargs ) if rejection_func: good_samps = [] for samp in samps.T: if rejection_func...
if full_output: out = { 'mean': mean, 'std': std, 'cov': covariance } if return_samples or full_MC: out['samp'] = samps if return_mean_func and self.mu is not None: out['mean_func'] = mean_func out['cov_func'] = scipy.zeros( (len(mean_func), len(mean_func)), dtype=float ) out['std_func'] = scipy.zeros_like(mean_func) o...
return mean else: return mean
def plot(self, X=None, n=0, ax=None, envelopes=[1, 3], base_alpha=0.375, return_prediction=False, return_std=True, full_output=False, plot_kwargs={}, **kwargs): """Plots the Gaussian process using the current hyperparameters. Only for num_dim <= 2. Parameters ---------- X : array-like (`M`,) or (`M`, `num_dim`), option...
process and a 50x50 grid is used for a bivariate Gaussian process. Default is None (use 100 points between min and max). n : int or list, optional The order of derivative to compute. For num_dim=1, this must be an int. For num_dim=2, this must be a list of ints of length 2. Default is 0 (don't take derivative). ax : ax...
Axis to plot the result on. If no axis is passed, one is created. If the string 'gca' is passed, the current axis (from plt.gca()) is used. If X_dim = 2, the axis must be 3d. envelopes: list of float, optional +/-n*sigma envelopes to plot. Default is [1, 3]. base_alpha : float, optional Alpha value to use for +/-1*sigm...
are drawn with `base_alpha`/`env`. Default is 0.375. return_prediction : bool, optional If True, the predicted values are also returned. Default is False. return_std : bool, optional If True, the standard deviation is computed and returned along with the mean when `return_prediction` is True. Default is True. full_outp...
========================================================================== mean mean of GP at requested points std standard deviation of GP at requested points cov covariance matrix for values of GP at requested points samp random samples of GP at requested points (only if `return_sample` is True) ==== ================...
this to, for instance, change the color, line width and line style. **kwargs : extra arguments for predict, optional Extra arguments that are passed to :py:meth:`predict`. Returns ------- ax : axis instance The axis instance used. mean : :py:class:`Array`, (`M`,) Predicted GP mean. Only returned if `return_prediction` ...
and `return_std` are True and `full_output` is False. full_output : dict Dictionary with fields for mean, std, cov and possibly random samples. Only returned if `return_prediction` and `full_output` are True. """ if self.num_dim > 2: raise ValueError("Plotting is not supported for num_dim > 2!") if self.num_dim == 1: i...
None: x1 = scipy.linspace(self.X[:, 0].min(), self.X[:, 0].max(), 50) x2 = scipy.linspace(self.X[:, 1].min(), self.X[:, 1].max(), 50) X1, X2 = scipy.meshgrid(x1, x2) X1 = X1.flatten() X2 = X2.flatten() X = scipy.hstack((scipy.atleast_2d(X1).T, scipy.atleast_2d(X2).T)) else: X1 = scipy.asarray(X[:, 0]).flatten() X2 = sc...