本文整理匯總了Python中skopt.space.Integer方法的典型用法代碼示例。如果您正苦於以下問題:Python space.Integer方法的具體用法?Python space.Integer怎麽用?Python space.Integer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類skopt.space
的用法示例。
在下文中一共展示了space.Integer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: bayes_search
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def bayes_search(self, **kwargs):
"""
Grid search using skopt.BayesSearchCV
Any parameters typically associated with BayesSearchCV (see
Scikit-Optimize documentation) can be passed as keyword arguments to
this function.
The final dictionary used for the grid search is saved to
`self.bayes_search_params`. This is updated with any parameters that
are passed.
Examples
--------
# Passing kwargs.
self.bayes_search(search_spaces={'max_depth':Integer(4, 6)}, refit=True)
"""
self.bayes_search_params.update(kwargs)
self.bayes_search_ = BayesSearchCV(**self.bayes_search_params)
self.bayes_search_.fit(self.x_train, self.transformed_y_train)
return self.bayes_search_
示例2: test_dimension_name
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_dimension_name():
notnames = [1, 1., 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])]
示例3: _knob_to_dimension
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def _knob_to_dimension(knob):
if isinstance(knob, CategoricalKnob):
return Categorical([x.value for x in knob.values])
elif isinstance(knob, IntegerKnob):
return Integer(knob.value_min, knob.value_max)
elif isinstance(knob, FloatKnob):
if knob.is_exp:
# Avoid error in skopt when low/high are 0
value_min = knob.value_min if knob.value_min != 0 else 1e-12
value_max = knob.value_max if knob.value_max != 0 else 1e-12
return Real(value_min, value_max, 'log-uniform')
else:
return Real(knob.value_min, knob.value_max, 'uniform')
else:
raise UnsupportedKnobError(knob.__class__)
示例4: _fit_svc
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
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, 1e+3, prior='log-uniform'),
'gamma': Real(1e-3, 1e+1, 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, 1e+3, prior='log-uniform'),
'gamma': Real(1e-3, 1e+1, 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)
示例5: test_searchcv_rank
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
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, 1e+6, prior='log-uniform'),
'gamma': Real(1e-6, 1e+1, 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)
示例6: test_dimensions
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_dimensions():
check_dimension(Real, (1., 4.), 2.251066014107722)
check_dimension(Real, (1, 4), 2.251066014107722)
check_dimension(Integer, (1, 4), 2)
check_dimension(Integer, (1., 4.), 2)
check_dimension(Integer, (1, 4), 2)
check_categorical(("a", "b", "c", "d"), "b")
check_categorical((1., 2., 3., 4.), 2.)
check_categorical((1, 2, 3, 4), 2)
示例7: test_integer
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_integer():
a = Integer(1, 10)
for i in range(50):
r = a.rvs(random_state=i)
assert 1 <= r
assert 11 >= r
assert r in a
random_values = a.rvs(random_state=0, n_samples=10)
assert_array_equal(random_values.shape, (10))
assert_array_equal(a.transform(random_values), random_values)
assert_array_equal(a.inverse_transform(random_values), random_values)
示例8: test_normalize_types
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_normalize_types():
# can you pass a Space instance to the Space constructor?
space = Space([(0.0, 1.0), Integer(-5, 5, dtype=int), (True, False)])
space.set_transformer("normalize")
X = [[0., -5, False]]
Xt = np.zeros((1, 3))
assert_array_equal(space.transform(X), Xt)
assert_array_equal(space.inverse_transform(Xt), X)
assert_array_equal(space.inverse_transform(space.transform(X)), X)
assert isinstance(space.inverse_transform(Xt)[0][0], float)
assert isinstance(space.inverse_transform(Xt)[0][1], int)
assert isinstance(space.inverse_transform(Xt)[0][2], (np.bool_, bool))
示例9: test_valid_transformation
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_valid_transformation():
check_valid_transformation(Integer)
check_valid_transformation(Real)
示例10: test_integer_distance
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_integer_distance():
ints = Integer(1, 10)
for i in range(1, 10+1):
assert_equal(ints.distance(4, i), abs(4 - i))
示例11: test_integer_distance_out_of_range
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_integer_distance_out_of_range():
ints = Integer(1, 10)
assert_raises_regex(RuntimeError, "compute distance for values within",
ints.distance, 11, 10)
示例12: test_space_from_yaml
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_space_from_yaml():
with NamedTemporaryFile(delete=False) as tmp:
tmp.write(b"""
Space:
- Real:
low: 0.0
high: 1.0
- Integer:
low: -5
high: 5
- Categorical:
categories:
- a
- b
- c
- Real:
low: 1.0
high: 5.0
prior: log-uniform
- Categorical:
categories:
- e
- f
""")
tmp.flush()
space = Space([(0.0, 1.0),
(-5, 5),
("a", "b", "c"),
(1.0, 5.0, "log-uniform"),
("e", "f")])
space2 = Space.from_yaml(tmp.name)
assert_equal(space, space2)
tmp.close()
os.unlink(tmp.name)
示例13: test_space_names_in_use_named_args
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def test_space_names_in_use_named_args():
space = [Integer(250, 2000, name='n_estimators')]
@use_named_args(space)
def objective(n_estimators):
return n_estimators
res = gp_minimize(objective, space, n_calls=10, random_state=0)
best_params = dict(zip((s.name for s in res.space), res.x))
assert 'n_estimators' in best_params
assert res.space.dimensions[0].name == 'n_estimators'
示例14: __init__
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
def __init__(self, configspace, **kwargs):
super().__init__(
configspace, reward_attribute=kwargs.get('reward_attribute'))
self.hp_ordering = configspace.get_hyperparameter_names() # fix order of hyperparams in configspace.
skopt_hpspace = []
for hp in self.hp_ordering:
hp_obj = configspace.get_hyperparameter(hp)
hp_type = str(type(hp_obj)).lower() # type of hyperparam
if 'integer' in hp_type:
hp_dimension = Integer(low=int(hp_obj.lower), high=int(hp_obj.upper),name=hp)
elif 'float' in hp_type:
if hp_obj.log: # log10-scale hyperparmeter
hp_dimension = Real(low=float(hp_obj.lower), high=float(hp_obj.upper), prior='log-uniform', name=hp)
else:
hp_dimension = Real(low=float(hp_obj.lower), high=float(hp_obj.upper), name=hp)
elif 'categorical' in hp_type:
hp_dimension = Categorical(hp_obj.choices, name=hp)
elif 'ordinal' in hp_type:
hp_dimension = Categorical(hp_obj.sequence, name=hp)
else:
raise ValueError("unknown hyperparameter type: %s" % hp)
skopt_hpspace.append(hp_dimension)
skopt_keys = {
'base_estimator', 'n_random_starts', 'n_initial_points',
'acq_func', 'acq_optimizer', 'random_state', 'model_queue_size',
'acq_func_kwargs', 'acq_optimizer_kwargs'}
skopt_kwargs = self._filter_skopt_kwargs(kwargs, skopt_keys)
self.bayes_optimizer = Optimizer(
dimensions=skopt_hpspace, **skopt_kwargs)
示例15: test_searchcv_runs
# 需要導入模塊: from skopt import space [as 別名]
# 或者: from skopt.space import Integer [as 別名]
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, 1e+6, prior='log-uniform'),
'gamma': Real(1e-6, 1e+1, 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