Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Black box optimizer example #13

Open
KOLANICH opened this issue Aug 20, 2018 · 2 comments
Open

Black box optimizer example #13

KOLANICH opened this issue Aug 20, 2018 · 2 comments

Comments

@KOLANICH
Copy link

KOLANICH commented Aug 20, 2018

import hyperengine
import numpy as np

def rosenbrock(hyperparams):
	return (hyperparams["x"]-1)**2 + 10*(hyperparams["x"]**2-hyperparams["y"])**2

class BlackBoxSolver:
	def __init__(self, func):
		self.func=func
		self._val_loss_curve = []

	def train(self):
		loss=self.func()
		self._val_loss_curve.append(loss)
		return self._reducer(self._val_loss_curve)
	
	def _reducer(self, *args, **kwargs):
		return np.min(*args, **kwargs)
	
	def terminate(self):
		pass

def solver_generator(hyperparams):
	return BlackBoxSolver(partial(rosenbrock, hyperparams))

class IterLimitedHyperTuner(hyperengine.HyperTuner):
	def __init__(self, hyper_params_spec, solver_generator, iterLimit, *args, **kwargs):
		j=0
		def solver_generator_limited(hyperparams):
			nonlocal j
			if j<iterLimit:
				j+=1
				return solver_generator(hyperparams)
			else:
				raise StopIteration()
		
		super().__init__(hyper_params_spec, solver_generator_limited, *args, **kwargs)
	
	def tune(self):
		try:
			super().tune()
		except StopIteration as ex:
			minLossPointNum=np.argmin(self.strategy.values)
			return dict(zip(self.parsed._spec.keys(), self.strategy.points[minLossPointNum]))


spec=hp.new({
	"x": hp.uniform(-10, 10),
	"y": hp.uniform(-10, 10),
})
tuner=IterLimitedHyperTuner(spec, solver_generator, iterLimit=10, strategy='bayesian') #'portfolio'
tuner.tune()
@maxim5
Copy link
Owner

maxim5 commented Aug 28, 2018

@KOLANICH Can you describe this code please?

@KOLANICH
Copy link
Author

The lower part is a workaround for then missing iteration limit. The upper part is an adapter adapting any function into HyperSolver-compatible object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants