4from typing
import Callable, Dict, List, Any, Union, Iterable
8 Iterator for Latin Hypercube Sampling (LHS) parameter search.
12 - **suggest_fn** : Callable[[Trial], Dict[str, Any]]
13 A function that suggests parameters
for each trial. It takes a Trial object
as input
and returns a dictionary representing the suggested parameters.
15 The number of samples to generate.
19 - **save** : Saves the LHSIterator object to a file using pickle serialization.
20 - **load** : Loads an LHSIterator object
from a file using pickle deserialization.
25 suggest_categorical(name: str, choices: List)
27 suggest_int(name: str, low: int, high: int, log: bool =
False, step: int =
None)
29 suggest_float(name: str, low: float, high: float, log: bool =
False, step: float =
None)
36 def suggest_params(trial: LHSIterator.Trial) -> Dict[str, Any]:
41 'hypothesis': trial.suggest_categorical(
"hypothesis", [
False,
True]),
42 'cycleDuration': trial.suggest_float(
"duration", 10.5, 20.3),
53 lhs_iterator.save(
"lhs_iterator.pkl")
56 loaded_iterator = LHSIterator.load(
"lhs_iterator.pkl")
58 for i, sample
in enumerate(loaded_iterator):
59 print(f
"Sample {i+1}: {sample}")
63 def __init__(self, param_space: Dict[str, Any]):
71 if name
in self.
param_space:
raise ValueError(f
"Parameter name '{name}' already exists in the parameter space.")
72 self.
param_space[name] = {
"type":
"categorical",
"choices": choices}
74 def suggest_int(self, name: str, low: int, high: int, log: bool =
False, step: int =
None) -> Any:
77 if name
in self.
param_space:
raise ValueError(f
"Parameter name '{name}' already exists in the parameter space.")
78 self.
param_space[name] = {
"type":
"int",
"low": low,
"high": high}
80 if step
is not None: self.
param_space[name][
'step'] = step
82 def suggest_float(self, name: str, low: float, high: float, log: bool =
False, step: float =
None) -> Any:
85 if name
in self.
param_space:
raise ValueError(f
"Parameter name '{name}' already exists in the parameter space.")
86 self.
param_space[name] = {
"type":
"float",
"low": low,
"high": high}
88 if step
is not None: self.
param_space[name][
'step'] = step
90 def __init__(self, suggest_fn: Callable[[Any], Dict[str, Any]], n_samples: int):
91 self.param_space: Dict[str, Any] = {}
92 self.n_samples: int = n_samples
98 self.
trial.modeSuggest=
True
111 return self.n_samples
114 if self.
index >= self.n_samples:
123 for i, (param_name, param_info)
in enumerate(self.
trial.param_space.items()):
124 if param_info[
'type'] ==
'categorical':
125 params[param_name] = param_info[
'choices'][int(sample[i] * len(param_info[
'choices']))]
126 elif param_info[
'type'] ==
'int':
127 if param_info.get(
'log',
False):
128 low = np.log(param_info[
'low'])
129 high = np.log(param_info[
'high'])
130 params[param_name] = int(np.exp(sample[i] * (high - low) + low))
131 elif 'step' in param_info:
132 params[param_name] = param_info[
'low'] + int(sample[i] * ((param_info[
'high'] - param_info[
'low']) // param_info[
'step'])) * param_info[
'step']
134 params[param_name] = param_info[
'low'] + int(sample[i] * (param_info[
'high'] - param_info[
'low'] + 1))
135 elif param_info[
'type'] ==
'float':
136 if param_info.get(
'log',
False):
137 low = np.log(param_info[
'low'])
138 high = np.log(param_info[
'high'])
139 params[param_name] = np.exp(sample[i] * (high - low) + low)
140 elif 'step' in param_info:
141 params[param_name] = param_info[
'low'] + int(sample[i] * ((param_info[
'high'] - param_info[
'low']) / param_info[
'step'])) * param_info[
'step']
143 params[param_name] = param_info[
'low'] + sample[i] * (param_info[
'high'] - param_info[
'low'])
148 cut = np.linspace(0, 1, samples + 1)
151 u = np.random.rand(samples, n)
153 b = cut[1:samples + 1]
154 rdpoints = np.zeros_like(u)
156 rdpoints[:, j] = u[:, j]*(b-a) + a
159 H = np.zeros_like(rdpoints)
161 order = np.random.permutation(range(samples))
162 H[:, j] = rdpoints[order, j]
166 def save(self, filename: str) ->
None:
168 Saves the LHSIterator object to a file using pickle serialization.
173 The name of the file to save the object to.
175 with open(filename,
'wb')
as f:
179 def load(filename: str) ->
'LHSIterator':
181 Loads an LHSIterator object from a file using pickle deserialization.
186 The name of the file to load the object
from.
191 The loaded LHSIterator object.
193 with open(filename,
'rb')
as f:
194 return pickle.load(f)
198 Converts the generated LHS samples into a pandas DataFrame.
203 A pandas DataFrame containing the generated LHS samples, where each row represents a sample and each column represents a parameter.
Any suggest_float(self, str name, float low, float high, bool log=False, float step=None)
Any suggest_int(self, str name, int low, int high, bool log=False, int step=None)
def __init__(self, Dict[str, Any] param_space)
Any suggest_categorical(self, str name, List[Union[str, int, float]] choices)
Dict[str, Any] _map_sample_to_params(self, np.ndarray sample)
Dict[str, Any] __next__(self)
'LHSIterator' __iter__(self)
def __init__(self, Callable[[Any], Dict[str, Any]] suggest_fn, int n_samples)
'LHSIterator' load(str filename)
np.ndarray _lhsclassic(self, int n, int samples)
pd.DataFrame toDataFrame(self)
None save(self, str filename)