physbo.search.range._policy のソースコード

# SPDX-License-Identifier: MPL-2.0
# Copyright (C) 2025- The University of Tokyo
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

import numpy as np
import pickle as pickle

from ._history import History
from .. import utility
from .. import score as search_score
from ... import _mpi
from ..._variable import Variable, normalize_t
from .._policy_common import _PolicyBase
from .._space import _RangeSpace, _space_attribute


[ドキュメント] class Policy(_PolicyBase): """Single objective Bayesian optimization with continuous search space""" min_X = _space_attribute( "min_X", "The minimum value of each dimension of the search space." ) max_X = _space_attribute( "max_X", "The maximum value of each dimension of the search space." ) L_X = _space_attribute("L_X", "The width of each dimension, max_X - min_X.") dim = _space_attribute("dim", "The number of dimensions of the search space.") constraint = _space_attribute( "constraint", "The inequality constraints on the search space (a callable), or None.", ) #: Rejection sampling of N feasible points is given up after max_trials_per_point * N samples. max_trials_per_point = 10000 def __init__( self, *, min_X=None, max_X=None, constraint=None, config=None, initial_data=None, comm=None, rng=None, ): """ Parameters ---------- 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. """ super().__init__( space=_RangeSpace(min_X, max_X, constraint), config=config, initial_data=initial_data, comm=comm, rng=rng, ) def _new_history(self): return History(dim=self.dim) def _write_initial_data(self, initial_data): if len(initial_data) != 2: msg = "ERROR: initial_data should be 2-elements tuple or list (X and objectives)" raise RuntimeError(msg) init_X, fs = initial_data fs_normalized = normalize_t(fs, k=1) assert init_X.shape[0] == fs_normalized.shape[0], ( "The number of initial data must be the same" ) assert init_X.shape[1] == self.dim, ( "The dimension of initial_data[0] must be the same as the dimension of min_X and max_X" ) self.write(init_X, fs_normalized) def _show_search_results(self, N_indeed, disp_pareto_set): self.history.show_search_results(N_indeed)
[ドキュメント] def write( self, 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). Parameters ---------- 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. Returns ------- Raises ------ ValueError If t contains a non-finite value (NaN or +-Inf). Nothing is written to the history in this case. """ # Normalize t to (N, 1) shape t_normalized = normalize_t(t, k=1) utility.require_finite(X, t_normalized) self.history.write( t.flatten(), X, time_total=time_total, time_update_predictor=time_update_predictor, time_get_action=time_get_action, time_run_simulator=time_run_simulator, ) # Get basis and convert to (1, N, n) format for single-objective Z_basis = self.predictor.get_basis(X) if self.predictor is not None else None if Z_basis is not None: Z = Z_basis[np.newaxis, :, :] # (N, n) -> (1, N, n) else: Z = None self.training.add(X=X, t=t_normalized, Z=Z) if self.new_data is None: self.new_data = Variable(X=X, t=t_normalized, Z=Z) else: self.new_data.add(X=X, t=t_normalized, Z=Z)
[ドキュメント] def get_post_fmean(self, xs): """ Calculate mean value of predictor (post distribution) Parameters ---------- xs: physbo.Variable or np.ndarray input parameters to calculate mean value shape is (num_points, num_parameters) Returns ------- fmean: numpy.ndarray Mean value of the post distribution. Returned shape is (num_points). """ X = self._make_variable_X(xs) if self.predictor is None: self._warn_no_predictor("get_post_fmean()") predictor = self._make_gp_predictor() predictor.fit(self.training, 0, comm=self.mpicomm, objective_index=0, rng=self.rng) predictor.prepare(self.training, objective_index=0) return predictor.get_post_fmean(self.training, X, objective_index=0) else: self._update_predictor() return self.predictor.get_post_fmean(self.training, X, objective_index=0)
[ドキュメント] def get_post_fcov(self, xs, diag=True): """ Calculate covariance of predictor (post distribution) Parameters ---------- 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. Returns ------- fcov: numpy.ndarray Covariance matrix of the post distribution. Returned shape is (num_points) if diag=true, (num_points, num_points) if diag=false. """ X = self._make_variable_X(xs) if self.predictor is None: self._warn_no_predictor("get_post_fcov()") predictor = self._make_gp_predictor() predictor.fit(self.training, 0, comm=self.mpicomm, objective_index=0, rng=self.rng) predictor.prepare(self.training, objective_index=0) return predictor.get_post_fcov(self.training, X, diag, objective_index=0) else: self._update_predictor() return self.predictor.get_post_fcov( self.training, X, diag, objective_index=0 )
[ドキュメント] def get_num_dim(self): """ Return the input dimension (number of features) of the search space. Returns ------- int The number of dimensions (from min_X / max_X). """ return self.dim
[ドキュメント] def get_score( self, mode, *, xs=None, predictor=None, training=None, parallel=True, alpha=1, ucb_beta=1.0, ): """ Calcualte score (acquisition function) Parameters ---------- 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. Returns ------- f: float or list of float Score defined in each mode. Raises ------ RuntimeError If both *actions* and *xs* are given Notes ----- 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. """ mode = search_score.resolve( mode, alpha=alpha, ucb_beta=ucb_beta, rng=self.rng ) if training is None: training = self.training if training.X is None or training.X.shape[0] == 0: msg = "ERROR: No training data is registered." raise RuntimeError(msg) if predictor is None: if self.predictor is None: self._warn_no_predictor("get_score()") predictor = self._make_gp_predictor() predictor.fit(training, 0, comm=self.mpicomm, objective_index=0, rng=self.rng) predictor.prepare(training, objective_index=0) else: self._update_predictor() predictor = self.predictor def scores(): # the share of this process of the candidates if xs is not None: test = self._make_variable_X(xs) if parallel and self.mpisize > 1: actions = np.array_split( np.arange(test.X.shape[0]), self.mpisize ) test = test.get_subset(actions[self.mpirank]) else: raise RuntimeError("ERROR: xs is not given") return search_score.score( mode, predictor=predictor, training=training, test=test, alpha=alpha, ucb_beta=ucb_beta, ) comm = self.mpicomm if parallel and self.mpisize > 1 else None f, error = _mpi.call(comm, scores) if comm is not None: fs = _mpi.allgather(comm, f, error) f = np.hstack(fs) return f
def _proposal_model(self): # copies of the predictor(s), prepared afresh from the training # data (which are not copied) predictors, training = self._current_model() model = (self._copy_predictors(predictors), training) self._prepare_model(model) return model def _default_optimizer(self): """Optimizer of the acquisition function used when none is given.""" return self.space.default_optimizer(self.rng, self.max_trials_per_point) def _get_random_action(self, N): return self.space.random( N, self.rng, self.mpicomm, max_trials_per_point=self.max_trials_per_point, )
[ドキュメント] def save(self, file_history, file_training=None, file_predictor=None): """ Saving history, training and predictor into the corresponding files. Parameters ---------- 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. Returns ------- Note ---- The constraint is not saved; give it to the constructor of the policy that loads the files. """ if self.mpirank == 0: self.history.save(file_history) if file_training is not None: self.training.save(file_training) if file_predictor is not None: with open(file_predictor, "wb") as f: pickle.dump(self.predictor, f)
[ドキュメント] def load(self, file_history, file_training=None, file_predictor=None): """ Loading files about history, training and predictor. Parameters ---------- 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. Returns ------- Note ---- The constraint is not restored by load(); the policy keeps the one given to its constructor. """ self.history.load(file_history) if file_training is None: # rebuild the training data from the valid observations only X, t = self.history.export_valid() # Normalize t to (N, 1) shape t_normalized = normalize_t(t, k=1) self.training = Variable(X=X, t=t_normalized) else: self.training = Variable() self.training.load(file_training) # Ensure t is normalized to (N, 1) shape after loading if self.training.t is not None: self.training.t = normalize_t(self.training.t, k=1) if file_predictor is not None: with open(file_predictor, "rb") as f: self.predictor = pickle.load(f) self._after_load()
def _learn_hyperparameter(self, num_rand_basis): self.predictor.fit( self.training, num_rand_basis, comm=self.mpicomm, objective_index=0, rng=self.rng, ) self._prepare_statistics() def _prepare_statistics(self): # Get basis and convert to (1, N, n) format for single-objective training_Z_basis = self.predictor.get_basis(self.training.X) if training_Z_basis is not None: self.training.Z = training_Z_basis[np.newaxis, :, :] # (N, n) -> (1, N, n) self.predictor.prepare(self.training, objective_index=0) self.new_data = None def _update_predictor(self): if self.new_data is not None: self.predictor.update(self.training, self.new_data, objective_index=0) self.new_data = None