physbo.search.discrete_multi package
Module contents
- class physbo.search.discrete_multi.History(num_objectives)[ソース]
ベースクラス:
_DiscreteMultiHistoryThe history of a multi-objective search in a discrete search space (physbo.search.discrete_multi.Policy).
The observations are in
fx(the objective values, one column per objective) andchosen_actions(the indexes of the actions), with one row per observation (total_num_searchof them).paretois the Pareto front of the observations.- パラメータ:
num_objectives (int) -- The number of objectives.
- property chosen_actions
The indexes of the actions of the observations (total_num_search entries).
- export_pareto_front()
Export the Pareto front of the valid observations.
- 戻り値:
front (numpy.ndarray) -- The objective values of the non-dominated observations, in ascending order of the first objective.
front_num (numpy.ndarray) -- The indexes of these observations in the history.
- 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). The reference points of the Pareto front are saved with it; the front itself is made again from the observations when the file is loaded.- パラメータ:
filename (str) -- The name of the file which stores the information of the history. It is used as it is (".npz" is not appended).
- show_search_results_mo(N, disp_pareto_set=False)
Print the last N observations, and the Pareto front if they have changed it (the front itself with
disp_pareto_set, else its size).
- 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_run_simulator
The elapsed time of running the simulator, for each step.
- property time_total
The elapsed time of the whole step, for each step.
- property time_update_predictor
The elapsed time of updating the predictor, for each step.
- 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, 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 (numpy.ndarray) -- N dimensional array. The indexes of the actions of the observations (or one index, 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.discrete_multi.Policy(test_X, num_objectives, comm=None, config=None, initial_data=None, rng=None)[ソース]
ベースクラス:
_MultiObjectiveMethods,PolicyMulti objective Bayesian optimization with discrete search space
- property actions
Array of action indices that have not been searched yet.
Initially contains all candidate indices, and decreases as actions are evaluated.
- bayes_search(training_list=None, max_num_probes=None, num_search_each_probe=1, predictor_list=None, is_disp=True, disp_pareto_set=False, simulator=None, score='HVPI', interval=0, num_rand_basis=None, optimizer=None, unify_method=None, ard=None)[ソース]
Performing Bayesian optimization by using multi objective function
- パラメータ:
training_list (list of physbo.Variable, optional) -- The training datasets.
max_num_probes (int, optional) -- The maximum number of searching process by Bayesian optimization.
num_search_each_probe (int, optional) -- The number of searching by Bayesian optimization at each process.
predictor_list (list of predictor objects, optional) -- The predictor objects.
is_disp (bool, optional) -- If true, process messages are outputted.
disp_pareto_set (bool, optional) -- If true, Pareto set is displayed.
simulator (callable, optional) -- The simulator function.
score (str or callable) -- EHVI, HVPI, TS, or a callable called positionally as
score(predictor_list, training, test, pareto)returning a numpy.ndarray of shape (test.X.shape[0],), with larger values preferred. pareto is self.history.pareto and must be treated as read-only; marginal scores do not update it with virtual data. Empty test data skips the callable. Under MPI, the callable evaluates local points and must not perform collective communication.interval (int, optional) -- 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, optional) -- This is for compatibility with the range-based Policies.
unify_method (callable, optional) -- This is for compatibility with the unified-optimization Policies.
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.
- 戻り値:
history
- 戻り値の型:
history object (physbo.search.discrete_multi.History)
- config: SetConfig
Configuration object containing settings for learning and search.
- 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) for each objective.
- 戻り値:
List of length num_objectives; each element is the length scale(s) for that objective's GP, or None if not available.
- 戻り値の型:
list of numpy.ndarray or None
- get_num_dim()[ソース]
Return the input dimension (number of features) of the search space.
- 戻り値:
The number of dimensions. None if neither training nor test data is set.
- 戻り値の型:
int or None
- get_permutation_importance(n_perm: int, split_features_parallel=False)
Calculate permutation importance of models
- パラメータ:
n_perm (int) -- The number of permutations
split_features_parallel (bool) -- If true, split features in parallel.
- 戻り値:
importance_mean (numpy.ndarray) -- importance_mean (num_parameters, num_objectives)
importance_std (numpy.ndarray) -- importance_std (num_parameters, num_objectives)
- get_post_fcov(xs, diag=True)
Calculate covariance of predictors (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, num_objectives) if diag=true, (num_points, num_points, num_objectives) if diag=false.
- 戻り値の型:
numpy.ndarray
- get_post_fmean(xs)
Calculate mean value of predictors (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, num_objectives).
- 戻り値の型:
numpy.ndarray
- get_score(mode, actions=None, xs=None, predictor_list=None, training_list=None, pareto=None, parallel=True, alpha=1)[ソース]
Calculate multi-objective scores (acquisition function).
- パラメータ:
mode (str or callable) -- EHVI, HVPI, TS, or a callable called positionally as
mode(predictor_list, training, test, pareto)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 self.TS_candidate_num apply only to string modes.actions (array of int, optional) -- Candidate indices to evaluate. If neither actions nor xs is given, evaluate candidates not yet searched.
xs (physbo.Variable or numpy.ndarray, optional) -- Input parameters to calculate scores.
predictor_list (list of predictor objects, optional) -- Predictors for each objective. Defaults to self.predictor_list.
training_list (physbo.Variable, optional) -- Training dataset containing all objectives. Defaults to self.training.
pareto (Pareto, optional) -- Passed unchanged when provided; otherwise self.history.pareto is used. Treat it as read-only. Marginal scores use the observed history's Pareto front without adding virtual observations.
parallel (bool) -- Calculate scores in parallel by MPI (default: True).
alpha (float) -- Posterior sampling scale for string "TS" (default: 1). Ignored for callable modes.
- 戻り値:
f -- Acquisition scores of shape (num_points,).
- 戻り値の型:
numpy.ndarray
- 例外:
RuntimeError -- If both actions and xs are given.
メモ
When parallel is True, all ranks must receive the same input. To supply separate local inputs, set parallel=False and gather results yourself.
- history: History
History object storing search results including chosen actions,
objective function values, and timing information.
- load(file_history, file_training_list=None, file_predictor_list=None)[ソース]
Loading files about history, training and predictor.
See
savefor the difference from the checkpoint API (save_checkpoint/load_checkpoint).- パラメータ:
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.
- 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.randomstate 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
commattached.- 戻り値の型:
policy
- 例外:
RuntimeError -- If the checkpoint was taken with a different policy class, a different number of MPI processes, or an incompatible checkpoint format.
- load_predictor_list(file_name)
- load_training_list(file_name)
- mpicomm: Any | None
MPI communicator for parallel computation.
If None, MPI is not used (single process).
- mpirank: int
Rank of the current MPI process. Set to 0 if MPI is not used.
- mpisize: int
Number of MPI processes. Set to 1 if MPI is not used.
- new_data: Variable | None
New data that has been added to training but not yet to predictor.
Set to None after predictor is updated.
- predictor: Any | None
Predictor used for Bayesian optimization.
Base class is defined in physbo.predictor. If None, predictor is not yet initialized.
- random_search(max_num_probes, num_search_each_probe=1, simulator=None, is_disp=True, disp_pareto_set=False)[ソース]
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.discrete.History)
- save(file_history, file_training_list=None, file_predictor_list=None)[ソース]
Saving history, training and predictor into the corresponding files.
This persists the search results in a portable form (the files can be loaded by runs with a different number of MPI processes). To suspend and later resume an execution bit-exactly (including the random number generator state), use
save_checkpoint/load_checkpointinstead.- パラメータ:
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.
- 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.randomstate 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_checkpointrestores the state and resumes bit-exactly.
savepersists only the search results (portable across runs with different numbers of MPI processes).
- save_predictor_list(file_name)
- save_training_list(file_name)
- seed: int | None
Seed parameter for np.random. Set by set_seed() method.
- 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
mpisizeandmpirankstored in the policy state; a policy restored from a serial run accepts onlyNone.- 例外:
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.randomstate, 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
-------
- property test
The set of candidate search points (physbo.Variable).
Each row of X represents the feature vector of each search candidate.
- training: Variable
Training dataset containing pairs of input (X) and output (t).
Stores all evaluated data points.
- write(action, t, X=None, time_total=None, time_update_predictor=None, time_get_action=None, time_run_simulator=None)[ソース]
Writing history (update history, not output to a file).
- パラメータ:
action (numpy.ndarray) -- Indexes of actions.
t (numpy.ndarray) -- N dimensional array (1D) or N x k 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. A non-finite value (NaN or +-Inf) marks a failed evaluation: the action is recorded in the history and consumed, but the observation is excluded from the training data and the best-value tracking.
X (numpy.ndarray) -- N x d dimensional matrix. Each row of X denotes the d-dimensional feature vector of each search candidate.
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.
Note
In this function, (X, t, Z) is added to the training data set (self.training), but not yet to predictor (self.predictor). self.newdata means such data. To add (X, t, Z) to the predictor, call self._update_predictor() after self.write().