def test_same_set_of_points_ask(strategy, surrogate): """ For n_points not None, tests whether two consecutive calls to ask return the same sets of points. Parameters ---------- * `strategy` [string]: Name of the strategy to use during optimization. * `surrogate` [scikit-optimize surrogate class]: A class of the scikit-optimize surrogate used in Optimizer. """ optimizer = Optimizer( base_estimator=surrogate(), dimensions=[Real(-5.0, 10.0), Real(0.0, 15.0)], acq_optimizer="sampling", random_state=2, ) for i in range(n_steps): xa = optimizer.ask(n_points, strategy) xb = optimizer.ask(n_points, strategy) optimizer.tell(xa, [branin(v) for v in xa]) assert_equal(xa, xb) # check if the sets of points generated are equal
def test_reproducible_runs(strategy, surrogate): # two runs of the optimizer should yield exactly the same results optimizer = Optimizer( base_estimator=surrogate(random_state=1), dimensions=[Real(-5.0, 10.0), Real(0.0, 15.0)], acq_optimizer="sampling", random_state=1, ) points = [] for i in range(n_steps): x = optimizer.ask(n_points, strategy) points.append(x) optimizer.tell(x, [branin(v) for v in x]) # the x's should be exaclty as they are in `points` optimizer = Optimizer( base_estimator=surrogate(random_state=1), dimensions=[Real(-5.0, 10.0), Real(0.0, 15.0)], acq_optimizer="sampling", random_state=1, ) for i in range(n_steps): x = optimizer.ask(n_points, strategy) assert points[i] == x optimizer.tell(x, [branin(v) for v in x])
def test_constant_liar_runs(strategy, surrogate, acq_func): """ Tests whether the optimizer runs properly during the random initialization phase and beyond Parameters ---------- * `strategy` [string]: Name of the strategy to use during optimization. * `surrogate` [scikit-optimize surrogate class]: A class of the scikit-optimize surrogate used in Optimizer. """ optimizer = Optimizer( base_estimator=surrogate(), dimensions=[Real(-5.0, 10.0), Real(0.0, 15.0)], acq_func=acq_func, acq_optimizer="sampling", random_state=0, ) # test arguments check assert_raises(ValueError, optimizer.ask, {"strategy": "cl_maen"}) assert_raises(ValueError, optimizer.ask, {"n_points": "0"}) assert_raises(ValueError, optimizer.ask, {"n_points": 0}) for i in range(n_steps): x = optimizer.ask(n_points=n_points, strategy=strategy) # check if actually n_points was generated assert_equal(len(x), n_points) if "ps" in acq_func: optimizer.tell(x, [[branin(v), 1.1] for v in x]) else: optimizer.tell(x, [branin(v) for v in x])
def test_all_points_different(strategy, surrogate): """ Tests whether the parallel optimizer always generates different points to evaluate. Parameters ---------- * `strategy` [string]: Name of the strategy to use during optimization. * `surrogate` [scikit-optimize surrogate class]: A class of the scikit-optimize surrogate used in Optimizer. """ optimizer = Optimizer( base_estimator=surrogate(), dimensions=[Real(-5.0, 10.0), Real(0.0, 15.0)], acq_optimizer="sampling", random_state=1, ) tolerance = 1e-3 # distance above which points are assumed same for i in range(n_steps): x = optimizer.ask(n_points, strategy) optimizer.tell(x, [branin(v) for v in x]) distances = pdist(x) assert all(distances > tolerance)
def test_searchcv_sklearn_compatibility(): """ Test whether the BayesSearchCV is compatible with base sklearn methods such as clone, set_params, get_params. """ X, y = load_iris(True) X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=0) # used to try different model classes pipe = Pipeline([("model", SVC())]) # single categorical value of 'model' parameter sets the model class lin_search = { "model": Categorical([LinearSVC()]), "model__C": Real(1e-6, 1e6, prior="log-uniform"), } dtc_search = { "model": Categorical([DecisionTreeClassifier()]), "model__max_depth": Integer(1, 32), "model__min_samples_split": Real(1e-3, 1.0, prior="log-uniform"), } svc_search = { "model": Categorical([SVC()]), "model__C": Real(1e-6, 1e6, prior="log-uniform"), "model__gamma": Real(1e-6, 1e1, prior="log-uniform"), "model__degree": Integer(1, 8), "model__kernel": Categorical(["linear", "poly", "rbf"]), } opt = BayesSearchCV(pipe, [(lin_search, 1), svc_search], n_iter=2) opt_clone = clone(opt) params, params_clone = opt.get_params(), opt_clone.get_params() assert params.keys() == params_clone.keys() for param, param_clone in zip(params.items(), params_clone.items()): assert param[0] == param_clone[0] assert isinstance(param[1], type(param_clone[1])) opt.set_params(search_spaces=[(dtc_search, 1)]) opt.fit(X_train, y_train) opt_clone.fit(X_train, y_train) total_evaluations = len(opt.cv_results_["mean_test_score"]) total_evaluations_clone = len(opt_clone.cv_results_["mean_test_score"]) # test if expected number of subspaces is explored assert total_evaluations == 1 assert total_evaluations_clone == 1 + 2
def test_check_list_types(): # Define the search-space dimensions. They must all have names! dim1 = Real(name="foo", low=0.0, high=1.0) dim2 = Real(name="bar", low=0.0, high=1.0) dim3 = Real(name="baz", low=0.0, high=1.0) # Gather the search-space dimensions in a list. dimensions = [dim1, dim2, dim3] check_list_types(dimensions, Dimension) dimensions = [dim1, dim2, dim3, "test"] assert_raises(ValueError, check_list_types, dimensions, Dimension)
def test_real_log_sampling_in_bounds(): dim = Real(low=1, high=32, prior="log-uniform", transform="normalize") # round trip a value that is within the bounds of the space # # x = dim.inverse_transform(dim.transform(31.999999999999999)) for n in (32.0, 31.999999999999999): round_tripped = dim.inverse_transform(dim.transform([n])) assert np.allclose([n], round_tripped) assert n in dim assert round_tripped in dim
def test_use_named_args(): """ Test the function wrapper @use_named_args which is used for wrapping an objective function with named args so it can be called by the optimizers which only pass a single list as the arg. This test does not actually use the optimizers but merely simulates how they would call the function. """ # Define the search-space dimensions. They must all have names! dim1 = Real(name="foo", low=0.0, high=1.0) dim2 = Real(name="bar", low=0.0, high=1.0) dim3 = Real(name="baz", low=0.0, high=1.0) # Gather the search-space dimensions in a list. dimensions = [dim1, dim2, dim3] # Parameters that will be passed to the objective function. default_parameters = [0.5, 0.6, 0.8] # Define the objective function with named arguments # and use this function-decorator to specify the search-space dimensions. @use_named_args(dimensions=dimensions) def func(foo, bar, baz): # Assert that all the named args are indeed correct. assert foo == default_parameters[0] assert bar == default_parameters[1] assert baz == default_parameters[2] # Return some objective value. return foo**2 + bar**4 + baz**8 # Ensure the objective function can be called with a single # argument named x. res = func(x=default_parameters) assert isinstance(res, float) # Ensure the objective function can be called with a single # argument that is unnamed. res = func(default_parameters) assert isinstance(res, float) # Ensure the objective function can be called with a single # argument that is a numpy array named x. res = func(x=np.array(default_parameters)) assert isinstance(res, float) # Ensure the objective function can be called with a single # argument that is an unnamed numpy array. res = func(np.array(default_parameters)) assert isinstance(res, float)
def test_searchcv_runs(surrogate, n_jobs, n_points, cv=None): """ Test whether the cross validation search wrapper around sklearn models runs properly with available surrogates and with single or multiple workers and different number of parameter settings to ask from the optimizer in parallel. Parameters ---------- * `surrogate` [str or None]: A class of the scikit-optimize surrogate used. None means to use default surrogate. * `n_jobs` [int]: Number of parallel processes to use for computations. """ X, y = load_iris(True) X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=0) # create an instance of a surrogate if it is not a string if surrogate is not None: optimizer_kwargs = {"base_estimator": surrogate} else: optimizer_kwargs = None opt = BayesSearchCV( SVC(), { "C": Real(1e-6, 1e6, prior="log-uniform"), "gamma": Real(1e-6, 1e1, prior="log-uniform"), "degree": Integer(1, 8), "kernel": Categorical(["linear", "poly", "rbf"]), }, n_jobs=n_jobs, n_iter=11, n_points=n_points, cv=cv, optimizer_kwargs=optimizer_kwargs, ) opt.fit(X_train, y_train) # this normally does not hold only if something is wrong # with the optimizaiton procedure as such assert opt.score(X_test, y_test) > 0.9
def _fit_svc(n_jobs=1, n_points=1, cv=None): """ Utility function to fit a larger classification task with SVC """ X, y = make_classification( n_samples=1000, n_features=20, n_redundant=0, n_informative=18, random_state=1, n_clusters_per_class=1, ) opt = BayesSearchCV( SVC(), { "C": Real(1e-3, 1e3, prior="log-uniform"), "gamma": Real(1e-3, 1e1, prior="log-uniform"), "degree": Integer(1, 3), }, n_jobs=n_jobs, n_iter=11, n_points=n_points, cv=cv, random_state=42, ) opt.fit(X, y) assert opt.score(X, y) > 0.9 opt2 = BayesSearchCV( SVC(), { "C": Real(1e-3, 1e3, prior="log-uniform"), "gamma": Real(1e-3, 1e1, prior="log-uniform"), "degree": Integer(1, 3), }, n_jobs=n_jobs, n_iter=11, n_points=n_points, cv=cv, random_state=42, ) opt2.fit(X, y) assert opt.score(X, y) == opt2.score(X, y)
def test_searchcv_callback(): # Test whether callback is used in BayesSearchCV and # whether is can be used to interrupt the search loop X, y = load_iris(True) opt = BayesSearchCV( DecisionTreeClassifier(), { "max_depth": [3], # additional test for single dimension "min_samples_split": Real(0.1, 0.9), }, n_iter=5, ) total_iterations = [0] def callback(opt_result): # this simply counts iterations total_iterations[0] += 1 # break the optimization loop at some point if total_iterations[0] > 2: return True # True == stop optimization return False opt.fit(X, y, callback=callback) assert total_iterations[0] == 3 # test whether final model was fit opt.score(X, y)
def test_searchcv_runs_multiple_subspaces(): """ Test whether the BayesSearchCV runs without exceptions when multiple subspaces are given. """ X, y = load_iris(True) X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=0) # used to try different model classes pipe = Pipeline([("model", SVC())]) # single categorical value of 'model' parameter sets the model class lin_search = { "model": Categorical([LinearSVC()]), "model__C": Real(1e-6, 1e6, prior="log-uniform"), } dtc_search = { "model": Categorical([DecisionTreeClassifier()]), "model__max_depth": Integer(1, 32), "model__min_samples_split": Real(1e-3, 1.0, prior="log-uniform"), } svc_search = { "model": Categorical([SVC()]), "model__C": Real(1e-6, 1e6, prior="log-uniform"), "model__gamma": Real(1e-6, 1e1, prior="log-uniform"), "model__degree": Integer(1, 8), "model__kernel": Categorical(["linear", "poly", "rbf"]), } opt = BayesSearchCV(pipe, [(lin_search, 1), (dtc_search, 1), svc_search], n_iter=2) opt.fit(X_train, y_train) # test if all subspaces are explored total_evaluations = len(opt.cv_results_["mean_test_score"]) assert total_evaluations == 1 + 1 + 2, "Not all spaces were explored!" assert len(opt.optimizer_results_) == 3 assert isinstance(opt.optimizer_results_[0].x[0], LinearSVC) assert isinstance(opt.optimizer_results_[1].x[0], DecisionTreeClassifier) assert isinstance(opt.optimizer_results_[2].x[0], SVC)
def test_searchcv_reproducibility(): """ Test whether results of BayesSearchCV can be reproduced with a fixed random state. """ X, y = load_iris(True) X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=0) random_state = 42 opt = BayesSearchCV( SVC(random_state=random_state), { "C": Real(1e-6, 1e6, prior="log-uniform"), "gamma": Real(1e-6, 1e1, prior="log-uniform"), "degree": Integer(1, 8), "kernel": Categorical(["linear", "poly", "rbf"]), }, n_iter=11, random_state=random_state, ) opt.fit(X_train, y_train) best_est = opt.best_estimator_ optim_res = opt.optimizer_results_[0].x opt2 = clone(opt).fit(X_train, y_train) best_est2 = opt2.best_estimator_ optim_res2 = opt2.optimizer_results_[0].x assert getattr(best_est, "C") == getattr(best_est2, "C") assert getattr(best_est, "gamma") == getattr(best_est2, "gamma") assert getattr(best_est, "degree") == getattr(best_est2, "degree") assert getattr(best_est, "kernel") == getattr(best_est2, "kernel") # dict is sorted by alphabet assert optim_res[0] == getattr(best_est, "C") assert optim_res[2] == getattr(best_est, "gamma") assert optim_res[1] == getattr(best_est, "degree") assert optim_res[3] == getattr(best_est, "kernel") assert optim_res2[0] == getattr(best_est, "C") assert optim_res2[2] == getattr(best_est, "gamma") assert optim_res2[1] == getattr(best_est, "degree") assert optim_res2[3] == getattr(best_est, "kernel")
def test_searchcv_refit(): """ Test whether results of BayesSearchCV can be reproduced with a fixed random state. """ X, y = load_iris(True) X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=0) random_state = 42 opt = BayesSearchCV( SVC(random_state=random_state), { "C": Real(1e-6, 1e6, prior="log-uniform"), "gamma": Real(1e-6, 1e1, prior="log-uniform"), "degree": Integer(1, 8), "kernel": Categorical(["linear", "poly", "rbf"]), }, n_iter=11, random_state=random_state, ) opt2 = BayesSearchCV( SVC(random_state=random_state), { "C": Real(1e-6, 1e6, prior="log-uniform"), "gamma": Real(1e-6, 1e1, prior="log-uniform"), "degree": Integer(1, 8), "kernel": Categorical(["linear", "poly", "rbf"]), }, n_iter=11, random_state=random_state, refit=True, ) opt.fit(X_train, y_train) opt2.best_estimator_ = opt.best_estimator_ opt2.fit(X_train, y_train) # this normally does not hold only if something is wrong # with the optimizaiton procedure as such assert opt2.score(X_test, y_test) > 0.9
def test_real_bounds(): # should give same answer as using check_limits() but this is easier # to read a = Real(1.0, 2.1) assert 0.99 not in a assert 1.0 in a assert 2.09 in a assert 2.1 in a assert np.nextafter(2.1, 3.0) not in a
def test_dimension_name(): notnames = [1, 1.0, True] for n in notnames: with pytest.raises(ValueError) as exc: real = Real(1, 2, name=n) assert ("Dimension's name must be either string or" "None." == exc.value.args[0]) s = Space([ Real(1, 2, name="a"), Integer(1, 100, name="b"), Categorical(["red, blue"], name="c"), ]) assert s["a"] == (0, s.dimensions[0]) assert s["a", "c"] == [(0, s.dimensions[0]), (2, s.dimensions[2])] assert s[["a", "c"]] == [(0, s.dimensions[0]), (2, s.dimensions[2])] assert s[("a", "c")] == [(0, s.dimensions[0]), (2, s.dimensions[2])] assert s[0] == (0, s.dimensions[0]) assert s[0, "c"] == [(0, s.dimensions[0]), (2, s.dimensions[2])] assert s[0, 2] == [(0, s.dimensions[0]), (2, s.dimensions[2])]
def test_searchcv_rank(): """ Test whether results of BayesSearchCV can be reproduced with a fixed random state. """ X, y = load_iris(True) X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=0) random_state = 42 opt = BayesSearchCV( SVC(random_state=random_state), { "C": Real(1e-6, 1e6, prior="log-uniform"), "gamma": Real(1e-6, 1e1, prior="log-uniform"), "degree": Integer(1, 8), "kernel": Categorical(["linear", "poly", "rbf"]), }, n_iter=11, random_state=random_state, return_train_score=True, ) opt.fit(X_train, y_train) results = opt.cv_results_ test_rank = np.asarray(rankdata(-np.array(results["mean_test_score"]), method="min"), dtype=np.int32) train_rank = np.asarray(rankdata(-np.array(results["mean_train_score"]), method="min"), dtype=np.int32) assert_array_equal(np.array(results["rank_test_score"]), test_rank) assert_array_equal(np.array(results["rank_train_score"]), train_rank)
def test_searchcv_total_iterations(): # Test the total iterations counting property of BayesSearchCV opt = BayesSearchCV( DecisionTreeClassifier(), [ ({ "max_depth": (1, 32) }, 10), # 10 iterations here { "min_samples_split": Real(0.1, 0.9) }, # 5 (default) iters here ], n_iter=5, ) assert opt.total_iterations == 10 + 5
def test_dimensions_names(): from deephyper.skopt.space import Real, Categorical, Integer # create search space and optimizer space = [ Real(0, 1, name="real"), Categorical(["a", "b", "c"], name="cat"), Integer(0, 1, name="int"), ] opt = Optimizer(space, n_initial_points=2) # result of the optimizer missing dimension names result = opt.tell([(0.5, "a", 0.5)], [3]) names = [] for d in result.space.dimensions: names.append(d.name) assert len(names) == 3 assert "real" in names assert "cat" in names assert "int" in names assert None not in names
@pytest.mark.parametrize( "dimension, bounds", [(Real, (2, 1)), (Integer, (2, 1)), (Real, (2, 2)), (Integer, (2, 2))], ) def test_dimension_bounds(dimension, bounds): with pytest.raises(ValueError) as exc: dim = dimension(*bounds) assert "has to be less than the upper bound " in exc.value.args[0] @pytest.mark.parametrize( "dimension, name", [ (Real(1, 2, name="learning_rate"), "learning_rate"), (Integer(1, 100, name="n_trees"), "n_trees"), (Categorical(["red, blue"], name="colors"), "colors"), ], ) def test_dimension_name(dimension, name): assert dimension.name == name def test_dimension_name(): notnames = [1, 1.0, True] for n in notnames: with pytest.raises(ValueError) as exc: real = Real(1, 2, name=n) assert ("Dimension's name must be either string or" "None." == exc.value.args[0])
def test_space_consistency(): # Reals (uniform) s1 = Space([Real(0.0, 1.0)]) s2 = Space([Real(0.0, 1.0)]) s3 = Space([Real(0, 1)]) s4 = Space([(0.0, 1.0)]) s5 = Space([(0.0, 1.0, "uniform")]) s6 = Space([(0, 1.0)]) s7 = Space([(np.float64(0.0), 1.0)]) s8 = Space([(0, np.float64(1.0))]) a1 = s1.rvs(n_samples=10, random_state=0) a2 = s2.rvs(n_samples=10, random_state=0) a3 = s3.rvs(n_samples=10, random_state=0) a4 = s4.rvs(n_samples=10, random_state=0) a5 = s5.rvs(n_samples=10, random_state=0) assert_equal(s1, s2) assert_equal(s1, s3) assert_equal(s1, s4) assert_equal(s1, s5) assert_equal(s1, s6) assert_equal(s1, s7) assert_equal(s1, s8) assert_array_equal(a1, a2) assert_array_equal(a1, a3) assert_array_equal(a1, a4) assert_array_equal(a1, a5) # Reals (log-uniform) s1 = Space([Real(10**-3.0, 10**3.0, prior="log-uniform", base=10)]) s2 = Space([Real(10**-3.0, 10**3.0, prior="log-uniform", base=10)]) s3 = Space([Real(10**-3, 10**3, prior="log-uniform", base=10)]) s4 = Space([(10**-3.0, 10**3.0, "log-uniform", 10)]) s5 = Space([(np.float64(10**-3.0), 10**3.0, "log-uniform", 10)]) a1 = s1.rvs(n_samples=10, random_state=0) a2 = s2.rvs(n_samples=10, random_state=0) a3 = s3.rvs(n_samples=10, random_state=0) a4 = s4.rvs(n_samples=10, random_state=0) assert_equal(s1, s2) assert_equal(s1, s3) assert_equal(s1, s4) assert_equal(s1, s5) assert_array_equal(a1, a2) assert_array_equal(a1, a3) assert_array_equal(a1, a4) # Integers s1 = Space([Integer(1, 5)]) s2 = Space([Integer(1.0, 5.0)]) s3 = Space([(1, 5)]) s4 = Space([(np.int64(1.0), 5)]) s5 = Space([(1, np.int64(5.0))]) a1 = s1.rvs(n_samples=10, random_state=0) a2 = s2.rvs(n_samples=10, random_state=0) a3 = s3.rvs(n_samples=10, random_state=0) assert_equal(s1, s2) assert_equal(s1, s3) assert_equal(s1, s4) assert_equal(s1, s5) assert_array_equal(a1, a2) assert_array_equal(a1, a3) # Integers (log-uniform) s1 = Space([Integer(16, 512, prior="log-uniform", base=2)]) s2 = Space([Integer(16.0, 512.0, prior="log-uniform", base=2)]) s3 = Space([(16, 512, "log-uniform", 2)]) s4 = Space([(np.int64(16.0), 512, "log-uniform", 2)]) s5 = Space([(16, np.int64(512.0), "log-uniform", 2)]) a1 = s1.rvs(n_samples=10, random_state=0) a2 = s2.rvs(n_samples=10, random_state=0) a3 = s3.rvs(n_samples=10, random_state=0) assert_equal(s1, s2) assert_equal(s1, s3) assert_equal(s1, s4) assert_equal(s1, s5) assert_array_equal(a1, a2) assert_array_equal(a1, a3) # Categoricals s1 = Space([Categorical(["a", "b", "c"])]) s2 = Space([Categorical(["a", "b", "c"])]) s3 = Space([["a", "b", "c"]]) a1 = s1.rvs(n_samples=10, random_state=0) a2 = s2.rvs(n_samples=10, random_state=0) a3 = s3.rvs(n_samples=10, random_state=0) assert_equal(s1, s2) assert_array_equal(a1, a2) assert_equal(s1, s3) assert_array_equal(a1, a3) s1 = Space([(True, False)]) s2 = Space([Categorical([True, False])]) s3 = Space([np.array([True, False])]) assert s1 == s2 == s3 # Categoricals Integer s1 = Space([Categorical([1, 2, 3])]) s2 = Space([Categorical([1, 2, 3])]) s3 = Space([[1, 2, 3]]) a1 = s1.rvs(n_samples=10, random_state=0) a2 = s2.rvs(n_samples=10, random_state=0) a3 = s3.rvs(n_samples=10, random_state=0) assert_equal(s1, s2) assert_array_equal(a1, a2) assert_equal(s1, s3) assert_array_equal(a1, a3) s1 = Space([(True, False)]) s2 = Space([Categorical([True, False])]) s3 = Space([np.array([True, False])]) assert s1 == s2 == s3
def test_normalize_real(): a = Real(2.0, 30.0, transform="normalize") for i in range(50): check_limits(a.rvs(random_state=i), 2, 30) rng = np.random.RandomState(0) X = rng.randn(100) X = 28 * (X - X.min()) / (X.max() - X.min()) + 2 # Check transformed values are in [0, 1] assert np.all(a.transform(X) <= np.ones_like(X)) assert np.all(np.zeros_like(X) <= a.transform(X)) # Check inverse transform assert_array_almost_equal(a.inverse_transform(a.transform(X)), X) # log-uniform prior a = Real(10**2.0, 10**4.0, prior="log-uniform", transform="normalize") for i in range(50): check_limits(a.rvs(random_state=i), 10**2, 10**4) rng = np.random.RandomState(0) X = np.clip(10**3 * rng.randn(100), 10**2.0, 10**4.0) # Check transform assert np.all(a.transform(X) <= np.ones_like(X)) assert np.all(np.zeros_like(X) <= a.transform(X)) # Check inverse transform assert_array_almost_equal(a.inverse_transform(a.transform(X)), X) a = Real(0, 1, transform="normalize", dtype=float) for i in range(50): check_limits(a.rvs(random_state=i), 0, 1) assert_array_equal(a.transformed_bounds, (0, 1)) X = rng.rand() # Check transformed values are in [0, 1] assert np.all(a.transform(X) <= np.ones_like(X)) assert np.all(np.zeros_like(X) <= a.transform(X)) # Check inverse transform X_orig = a.inverse_transform(a.transform(X)) assert isinstance(X_orig, float) assert_array_equal(X_orig, X) a = Real(0, 1, transform="normalize", dtype="float64") X = np.float64(rng.rand()) # Check inverse transform X_orig = a.inverse_transform(a.transform(X)) assert isinstance(X_orig, np.float64) a = Real(0, 1, transform="normalize", dtype=np.float64) X = np.float64(rng.rand()) # Check inverse transform X_orig = a.inverse_transform(a.transform(X)) assert isinstance(X_orig, np.float64) a = Real(0, 1, transform="normalize", dtype="float64") X = np.float64(rng.rand()) # Check inverse transform X_orig = a.inverse_transform(a.transform(X)) assert isinstance(X_orig, np.float64)
def test_real_distance_out_of_range(): ints = Real(1, 10) assert_raises_regex(RuntimeError, "compute distance for values within", ints.distance, 11, 10)
def test_real_distance(): reals = Real(1, 10) for i in range(1, 10 + 1): assert_equal(reals.distance(4.1234, i), abs(4.1234 - i))
def test_real(): a = Real(1, 25) for i in range(50): r = a.rvs(random_state=i) check_limits(r, 1, 25) assert r in a random_values = a.rvs(random_state=0, n_samples=10) assert len(random_values) == 10 assert_array_equal(a.transform(random_values), random_values) assert_array_equal(a.inverse_transform(random_values), random_values) log_uniform = Real(10**-5, 10**5, prior="log-uniform") assert log_uniform != Real(10**-5, 10**5) for i in range(50): random_val = log_uniform.rvs(random_state=i) check_limits(random_val, 10**-5, 10**5) random_values = log_uniform.rvs(random_state=0, n_samples=10) assert len(random_values) == 10 transformed_vals = log_uniform.transform(random_values) assert_array_equal(transformed_vals, np.log10(random_values)) assert_array_equal(log_uniform.inverse_transform(transformed_vals), random_values)
def test_dimension_with_invalid_names(name): with pytest.raises(ValueError) as exc: Real(1, 2, name=name) assert "Dimension's name must be either string or None." == exc.value.args[ 0]
[ (((1, 3), (1.0, 3.0)), ("normalize", "normalize")), (((1, 3), ("a", "b", "c")), ("normalize", "onehot")), ], ) def test_normalize_dimensions(dimensions, normalizations): space = normalize_dimensions(dimensions) for dimension, normalization in zip(space, normalizations): assert dimension.transform_ == normalization @pytest.mark.hps_fast_test @pytest.mark.parametrize( "dimension, name", [ (Real(1, 2, name="learning rate"), "learning rate"), (Integer(1, 100, name="no of trees"), "no of trees"), (Categorical(["red, blue"], name="colors"), "colors"), ], ) def test_normalize_dimensions(dimension, name): space = normalize_dimensions([dimension]) assert space.dimensions[0].name == name @pytest.mark.hps_fast_test def test_use_named_args(): """ Test the function wrapper @use_named_args which is used for wrapping an objective function with named args so it can be called by the optimizers which only pass a single