physbo.search.range package

Module contents

class physbo.search.range.History(dim: int)[ソース]

ベースクラス: _RangeHistory

The history of a search for a single objective in a continuous search space (physbo.search.range.Policy).

The observations are in fx (the objective values) and action_X (the inputs), with one row per observation (total_num_search of them).

パラメータ:

dim (int) -- The dimension of the search space.

property action_X

The inputs of the observations (total_num_search x dim).

property best_index

The index of the best valid observation after each observation, -1 until the first valid one (total_num_search entries).

export_all_sequence_best_fx()

Export the best fx and its point after each observation. (The total number of data is total_num_search.)

Until the first valid observation, the best fx is NaN and the point is -1 (the index of an action) or NaN (the coordinates of a point).

戻り値:

  • best_fx (numpy.ndarray (total_num_search))

  • best_points (numpy.ndarray) -- The indexes of the actions (total_num_search) in a discrete search space, the inputs (total_num_search, dim) in a continuous one.

export_sequence_best_fx()

Export the best fx and its point at the end of each step (each call of write).

Until the first valid observation, the best fx is NaN and the point is -1 (the index of an action) or NaN (the coordinates of a point).

戻り値:

  • best_fx (numpy.ndarray (num_runs)) -- The best fx at the end of each step.

  • best_points (numpy.ndarray) -- The index of its action (num_runs) in a discrete search space, its input (num_runs, dim) in a continuous one.

export_valid()

Export the valid (successfully evaluated) observations.

戻り値:

  • points (numpy.ndarray) -- The points of the valid observations: the indexes of the actions in a discrete search space, the inputs (N_valid x dim) in a continuous one.

  • fx (numpy.ndarray) -- Objective values of the valid observations (N_valid x num_objectives for several objectives).

property fx

The objective values of the observations (total_num_search rows).

load(filename)

Load the information of the history, in place of what it holds.

The file is one written by save, of this or of an earlier version. If there is no file of this name but one with ".npz" appended (as numpy does when saving), that one is read.

パラメータ:

filename (str) -- The name of the file which stores the information of the history

例外:

ValueError -- If the file is not that of a history of this kind (an entry is missing, or the arrays do not have the shape of this history). The history is left as it was.

save(filename)

Save the information of the history, as an archive of numpy (numpy.savez_compressed).

パラメータ:

filename (str) -- The name of the file which stores the information of the history (numpy appends ".npz" if the name does not end with it)

show_search_results(N)

Print the last N observations and the best value so far.

property terminal_num_run

The number of observations at the end of each step (num_runs entries).

property time_get_action

The elapsed time of choosing the next points, for each step.

property time_get_action_
property time_run_simulator

The elapsed time of running the simulator, for each step.

property time_run_simulator_
property time_total

The elapsed time of the whole step, for each step.

property time_total_
property time_update_predictor

The elapsed time of updating the predictor, for each step.

property time_update_predictor_
property valid_mask

Mask of valid observations (True) vs failed ones (False).

An observation is failed when its objective value (any of them, for several objectives) is not finite (NaN or +-Inf). Failed observations are kept in the history but excluded from the training data and from the best value so far or the Pareto front.

戻り値の型:

numpy.ndarray of bool, shape (total_num_search,)

write(t, action_X, time_total=None, time_update_predictor=None, time_get_action=None, time_run_simulator=None)

Record the observations of one step.

パラメータ:
  • t (numpy.ndarray) -- The values of the objective function(s) of the observations (to be maximized). For a single objective, an N dimensional or an N x 1 array; for several objectives, an N x num_objectives array, or an array of num_objectives values for one observation.

  • action_X (numpy.ndarray) -- N x d dimensional array. The inputs of the observations (or an array of d values, for one observation).

  • time_total (numpy.ndarray) -- N dimensional array. The total elapsed time of the step, for each observation. If None (default), filled by 0.0.

  • time_update_predictor (numpy.ndarray) -- N dimensional array. The elapsed time for updating the predictor (e.g., learning the hyperparameters). If None (default), filled by 0.0.

  • time_get_action (numpy.ndarray) -- N dimensional array. The elapsed time for getting the next action. If None (default), filled by 0.0.

  • time_run_simulator (numpy.ndarray) -- N dimensional array. The elapsed time for running the simulator. If None (default), filled by 0.0.

  • step (Each elapsed time is that of the)

  • for (given once or repeated)

  • observation. (each)

例外:

ValueError -- If the numbers of objective values and of points differ, or if an argument does not have one of the shapes above. Nothing is written in this case.

class physbo.search.range.Policy(*, min_X=None, max_X=None, constraint=None, config=None, initial_data=None, comm=None, rng=None)[ソース]

ベースクラス: _PolicyBase

Single objective Bayesian optimization with continuous search space

パラメータ:
  • min_X (numpy.ndarray) -- The minimum value of each dimension of the search space.

  • max_X (numpy.ndarray) -- The maximum value of each dimension of the search space.

  • constraint (callable, optional) -- Inequality constraints on the search space. A function from an array of shape (N, d) to a boolean array of N elements (True for feasible points). Only feasible points are proposed by random_search and bayes_search. If None (default), the whole box [min_X, max_X] is searched. This is not saved by save(); pass it again to the constructor. It is part of the state pickled by save_checkpoint(), so it must be picklable (a function defined at module level or a method of a picklable object, not a lambda or a local function).

  • config (SetConfig object (physbo.misc.SetConfig))

  • initial_data (tuple[np.ndarray, np.ndarray]) -- The initial training datasets. The first elements is the array of inputs and the second is the array of values of objective functions These points are not checked against the constraint.

  • comm (MPI.Comm, optional) -- MPI Communicator

  • rng (None, "legacy", int, or numpy.random.Generator, optional) -- Random number generator specification (default: "legacy"). See physbo.search.discrete.Policy for details.

property L_X

The width of each dimension, max_X - min_X.

Performing Bayesian optimization.

パラメータ:
  • training (physbo.Variable) -- Training dataset.

  • max_num_probes (int) -- Maximum number of searching process by Bayesian optimization.

  • num_search_each_probe (int) -- Number of searching by Bayesian optimization at each process.

  • predictor (predictor object) -- Base class is defined in physbo.predictor. If None, blm_predictor is defined.

  • is_disp (bool) -- If true, process messages are outputted.

  • simulator (callable) -- Callable (function or object with __call__) Here, action is an integer which represents the index of the candidate.

  • score (str or callable) -- TS, EI, PI, UCB, or a callable called positionally as score(predictor, training, test) returning a numpy.ndarray of shape (test.X.shape[0],), with larger values preferred. Empty test data skips the callable. Under MPI, the callable evaluates local points and must not perform collective communication.

  • interval (int) -- The interval number of learning the hyper parameter. If you set the negative value to interval, the hyper parameter learning is not performed. If you set zero to interval, the hyper parameter learning is performed only at the first step. A negative interval needs a learned predictor: the one learned by an earlier bayes_search, or one given as an argument, read by load() or set by hand. Otherwise, or if another kind of predictor is asked for (see num_rand_basis), a RuntimeError is raised.

  • num_rand_basis (int, optional) -- The number of basis function. If you choose 0, ordinary Gaussian process run. If None (default), the predictor the policy has is used, whatever its kind; a Gaussian process is made if it has none yet. The predictor is kept between calls of bayes_search. A new one is made, to be learned, when the predictor is not of the kind asked for by num_rand_basis or ard.

  • optimizer (Optimizer object) -- Optimizer object for optimizing the acquisition function. If None, the default optimizer is used.

  • ard (bool, optional) -- If True, use Automatic Relevance Determination (ARD) for the Gaussian kernel. If None (default), as in the predictor the policy has; without ARD if it has none yet.

  • ucb_beta (float) -- Trade-off parameter between exploitation and exploration used for string "UCB". The score is fmean + ucb_beta * fstd. Default is 1.0; ignored for callable scores.

戻り値:

history

戻り値の型:

history object (physbo.search.range.History)

property constraint

The inequality constraints on the search space (a callable), or None.

property dim

The number of dimensions of the search space.

export_history()

Returning the information of the history.

export_predictor()

Returning the predictor dataset

export_training()

Returning the training dataset

get_kernel_length_scale()

Return the Gaussian kernel length scale(s) (width) of the predictor.

With ARD, returns one length scale per input dimension; otherwise a single value.

戻り値:

Length scale(s). Shape (num_dim,) when ARD is used, (1,) otherwise. None if the predictor is not set or not a GP with Gaussian kernel.

戻り値の型:

numpy.ndarray or None

get_num_dim()[ソース]

Return the input dimension (number of features) of the search space.

戻り値:

The number of dimensions (from min_X / max_X).

戻り値の型:

int

get_post_fcov(xs, diag=True)[ソース]

Calculate covariance of predictor (post distribution)

パラメータ:
  • xs (physbo.Variable or np.ndarray) -- input parameters to calculate covariance shape is (num_points, num_parameters)

  • diag (bool) -- If true, only variances (diagonal elements) are returned.

戻り値:

fcov -- Covariance matrix of the post distribution. Returned shape is (num_points) if diag=true, (num_points, num_points) if diag=false.

戻り値の型:

numpy.ndarray

get_post_fmean(xs)[ソース]

Calculate mean value of predictor (post distribution)

パラメータ:

xs (physbo.Variable or np.ndarray) -- input parameters to calculate mean value shape is (num_points, num_parameters)

戻り値:

fmean -- Mean value of the post distribution. Returned shape is (num_points).

戻り値の型:

numpy.ndarray

get_score(mode, *, xs=None, predictor=None, training=None, parallel=True, alpha=1, ucb_beta=1.0)[ソース]

Calcualte score (acquisition function)

パラメータ:
  • mode (str or callable) -- TS, EI, PI, UCB, or a callable called positionally as mode(predictor, training, test) returning a numpy.ndarray of shape (test.X.shape[0],), with larger values preferred. Empty test data skips the callable but still participates in MPI gathering. The callable must not perform collective communication. alpha and ucb_beta apply only to string modes.

  • xs (physbo.Variable or np.ndarray) -- input parameters to calculate score

  • predictor (predictor object) -- predictor used to calculate score. If not given, self.predictor will be used.

  • training (physbo.Variable) -- Training dataset. If not given, self.training will be used.

  • parallel (bool) -- Calculate scores in parallel by MPI (default: True)

  • alpha (float) -- Tuning parameter which is used if mode = TS. In TS, multi variation is tuned as np.random.multivariate_normal(mean, cov*alpha**2, size).

  • ucb_beta (float) -- Trade-off parameter between exploitation and exploration used for string "UCB". The score is fmean + ucb_beta * fstd. Default is 1.0; ignored for callable scores.

戻り値:

f -- Score defined in each mode.

戻り値の型:

float or list of float

例外:

RuntimeError -- If both actions and xs are given

メモ

When neither actions nor xs are given, scores for actions not yet searched will be calculated.

When parallel is True, it is assumed that the function receives the same input (actions or xs) for all the ranks. If you want to split the input array itself, set parallel be False and merge results by yourself.

load(file_history, file_training=None, file_predictor=None)[ソース]

Loading files about history, training and predictor.

パラメータ:
  • file_history (str) -- The name of the file that stores the information of the history.

  • file_training (str) -- The name of the file that stores the training dataset.

  • file_predictor (str) -- The name of the file that stores the predictor dataset.

Note

The constraint is not restored by load(); the policy keeps the one given to its constructor.

classmethod load_checkpoint(filename, comm=None)

Restore a policy from a checkpoint file.

Under MPI this is a collective operation: every rank must call it with the same filename; rank 0 reads the file and broadcasts it. The run must use the same number of MPI processes as the run that saved the checkpoint.

In the legacy RNG mode this restores the global numpy.random state of each rank as a side effect (the stream lives there); in the Generator mode the restored policy carries its own generator and the global state is not touched.

パラメータ:
  • filename (str) -- The name of the checkpoint file.

  • comm (MPI.Comm, optional) -- MPI communicator of the resuming run (default: None).

戻り値:

The restored policy, with comm attached.

戻り値の型:

policy

例外:

RuntimeError -- If the checkpoint was taken with a different policy class, a different number of MPI processes, or an incompatible checkpoint format.

property max_X

The maximum value of each dimension of the search space.

max_trials_per_point = 10000

Rejection sampling of N feasible points is given up after max_trials_per_point * N samples.

property min_X

The minimum value of each dimension of the search space.

Performing random search.

パラメータ:
  • max_num_probes (int) -- Maximum number of random search process.

  • num_search_each_probe (int) -- Number of search at each random search process.

  • simulator (callable) -- Callable (function or object with __call__) from action to t Here, action is an integer which represents the index of the candidate.

  • is_disp (bool) -- If true, process messages are outputted.

戻り値:

history

戻り値の型:

history object (physbo.search.range.History)

save(file_history, file_training=None, file_predictor=None)[ソース]

Saving history, training and predictor into the corresponding files.

パラメータ:
  • file_history (str) -- The name of the file that stores the information of the history.

  • file_training (str) -- The name of the file that stores the training dataset.

  • file_predictor (str) -- The name of the file that stores the predictor dataset.

Note

The constraint is not saved; give it to the constructor of the policy that loads the files.

save_checkpoint(filename)

Save the complete execution state into a single file.

Under MPI this is a collective operation: every rank must call it. The rank-local parts (remaining candidates and RNG state) are gathered, and rank 0 writes one file atomically (via a temporary file and os.replace).

In the legacy RNG mode the global numpy.random state of each rank is captured; in the Generator mode (rng= given to the policy) the policy-owned generators are stored.

パラメータ:

filename (str) -- The name of the checkpoint file.

参考

load_checkpoint

restores the state and resumes bit-exactly.

save

persists only the search results (portable across runs with different numbers of MPI processes).

set_comm(comm)

Re-attach an MPI communicator to a restored policy.

パラメータ:

comm (MPI.Comm or None) -- The communicator to attach. Its size and rank must match the mpisize and mpirank stored in the policy state; a policy restored from a serial run accepts only None.

例外:

RuntimeError -- If the communicator size or rank does not match the stored state.

set_seed(seed)

Setting a seed parameter.

In the legacy RNG mode (default), this seeds the global numpy.random state, as before. In the Generator mode (rng= given as int or Generator), the policy-owned generator is re-created from the seed and the global state is not touched.

パラメータ:
  • seed (int) -- seed number

  • -------

write(X, t, time_total=None, time_update_predictor=None, time_get_action=None, time_run_simulator=None)[ソース]

Writing history (update history, not output to a file).

パラメータ:
  • X (numpy.ndarray) -- N x d dimensional matrix. Each row of X denotes the d-dimensional feature vector of each search candidate.

  • t (numpy.ndarray) -- N dimensional array (1D) or N x 1 dimensional array (2D). The negative energy of each search candidate (value of the objective function to be optimized). Will be normalized to (N, 1) shape internally. All the values must be finite. Failed evaluations are not supported in continuous search spaces.

  • time_total (numpy.ndarray) -- N dimenstional array. The total elapsed time in each step. If None (default), filled by 0.0.

  • time_update_predictor (numpy.ndarray) -- N dimenstional array. The elapsed time for updating predictor (e.g., learning hyperparemters) in each step. If None (default), filled by 0.0.

  • time_get_action (numpy.ndarray) -- N dimenstional array. The elapsed time for getting next action in each step. If None (default), filled by 0.0.

  • time_run_simulator (numpy.ndarray) -- N dimenstional array. The elapsed time for running the simulator in each step. If None (default), filled by 0.0.

例外:

ValueError -- If t contains a non-finite value (NaN or +-Inf). Nothing is written to the history in this case.