def test_PoolContent(self): names = SolverPool.get_solver_names() self.assertTrue("hyperopt" in names) self.assertTrue("optunity" in names) self.assertTrue("optuna" in names) self.assertTrue("randomsearch" in names) self.assertTrue("quasirandomsearch" in names) self.assertTrue("gridsearch" in names)
def compute_deviation(solver_name, vfunc_id, iterations, N, fname): project = HyppopyProject() project.add_hyperparameter(name="axis_00", domain="uniform", data=[0, 1], dtype="float") project.add_hyperparameter(name="axis_01", domain="uniform", data=[0, 1], dtype="float") project.add_hyperparameter(name="axis_02", domain="uniform", data=[0, 1], dtype="float") project.add_hyperparameter(name="axis_03", domain="uniform", data=[0, 1], dtype="float") project.add_hyperparameter(name="axis_04", domain="uniform", data=[0, 1], dtype="float") vfunc = VirtualFunction() vfunc.load_default(vfunc_id) minima = vfunc.minima() def my_loss_function(data, params): return vfunc(**params) blackbox = BlackboxFunction(data=[], blackbox_func=my_loss_function) results = {} results["gt"] = [] for mini in minima: results["gt"].append(np.median(mini[0])) for iter in iterations: results[iter] = {"minima": {}, "loss": None} for i in range(vfunc.dims()): results[iter]["minima"]["axis_0{}".format(i)] = [] project.add_settings(section="solver", name="max_iterations", value=iter) project.add_settings(section="custom", name="use_solver", value=solver_name) solver = SolverPool.get(project=project) solver.blackbox = blackbox axis_minima = [] best_losses = [] for i in range(vfunc.dims()): axis_minima.append([]) for n in range(N): print("\rSolver={} iteration={} round={}".format(solver, iter, n), end="") solver.run(print_stats=False) df, best = solver.get_results() best_row = df['losses'].idxmin() best_losses.append(df['losses'][best_row]) for i in range(vfunc.dims()): tmp = df['axis_0{}'.format(i)][best_row] axis_minima[i].append(tmp) for i in range(vfunc.dims()): results[iter]["minima"]["axis_0{}".format(i)] = [np.mean(axis_minima[i]), np.std(axis_minima[i])] results[iter]["loss"] = [np.mean(best_losses), np.std(best_losses)] file = open(fname, 'wb') pickle.dump(results, file) file.close()
def test_getGridsearchSolver(self): config = { "hyperparameter": { "value 1": { "domain": "uniform", "data": [0, 20], "type": int, "frequency": 11 }, "value 2": { "domain": "normal", "data": [0, 20.0], "type": float, "frequency": 11 }, "value 3": { "domain": "loguniform", "data": [1, 10000], "type": float, "frequency": 11 }, "categorical": { "domain": "categorical", "data": ["a", "b"], "type": str, "frequency": 1 } } } res_labels = ['value 1', 'value 2', 'value 3', 'categorical'] res_values = [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20], [ 0.0, 5.467452952462635, 8.663855974622837, 9.755510546899107, 9.973002039367397, 10.0, 10.026997960632603, 10.244489453100893, 11.336144025377163, 14.532547047537365, 20.0 ], [ 1.0, 2.51188643150958, 6.309573444801933, 15.848931924611136, 39.810717055349734, 100.00000000000004, 251.18864315095806, 630.9573444801938, 1584.8931924611143, 3981.071705534977, 10000.00000000001 ], ['a', 'b']] project = HyppopyProject(config) solver = SolverPool.get("gridsearch", project) self.assertTrue(isinstance(solver, GridsearchSolver)) searchspace = solver.convert_searchspace(config["hyperparameter"]) for n in range(len(res_labels)): self.assertEqual(res_labels[n], searchspace[0][n]) for i in range(3): self.assertAlmostEqual(res_values[i], searchspace[1][i]) self.assertEqual(res_values[3], searchspace[1][3])
def test_projectNone(self): solver = SolverPool.get("hyperopt") solver = SolverPool.get("optunity") solver = SolverPool.get("optuna") solver = SolverPool.get("randomsearch") solver = SolverPool.get("quasirandomsearch") solver = SolverPool.get("gridsearch") self.assertRaises(AssertionError, SolverPool.get, "foo")
def test_getOptunitySolver(self): config = { "hyperparameter": { "axis_00": { "domain": "uniform", "data": [300, 800], "type": float }, "axis_01": { "domain": "uniform", "data": [-1, 1], "type": float }, "axis_02": { "domain": "uniform", "data": [0, 10], "type": float } }, "max_iterations": 100 } project = HyppopyProject(config) solver = SolverPool.get("optunity", project) self.assertTrue(isinstance(solver, OptunitySolver)) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(300 <= best['axis_00'] <= 800) self.assertTrue(-1 <= best['axis_01'] <= 1) self.assertTrue(0 <= best['axis_02'] <= 10) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float))
# as well as 2 dummy parameter (my_preproc_param, my_dataloader_input) for demonstration purposes. blackbox = BlackboxFunction(blackbox_func=my_loss_function, dataloader_func=my_dataloader_function, preprocess_func=my_preprocess_function, callback_func=my_callback_function, my_preproc_param=1, my_dataloader_input='could/be/a/path') # Last step, is we use our SolverPool which automatically returns the correct solver. # There are multiple ways to get the desired solver from the solver pool. # 1. solver = SolverPool.get('hyperopt') # solver.project = project # 2. solver = SolverPool.get('hyperopt', project) # 3. The SolverPool will look for the field 'use_solver' in the project instance, if # it is present it will be used to specify the solver so that in this case it is enough # to pass the project instance. solver = SolverPool.get(project=project) # Give the solver your blackbox and run it. After execution we can get the result # via get_result() which returns a pandas dataframe containing the complete history # The dict best contains the best parameter set. solver.blackbox = blackbox #solver.start_viewer() solver.run() df, best = solver.get_results() print("\n") print("*" * 100) print("Best Parameter Set:\n{}".format(best)) print("*" * 100)
"type": float, "frequency": 10 } }, "max_iterations": 500, "solver": "optunity" } project = HyppopyProject(config=config) # The user defined loss function def my_loss_function_params(params): x = params['x'] y = params['y'] return x**2 + y**3 solver = MPISolverWrapper(solver=SolverPool.get(project=project)) solver.blackbox = my_loss_function_params solver.run() df, best = solver.get_results() if solver.is_master() is True: print("\n") print("*" * 100) print("Best Parameter Set:\n{}".format(best)) print("*" * 100)
def compute_deviation(solver_name, vfunc_id, iterations, N, fname): project = HyppopyProject() project.add_hyperparameter(name="axis_00", domain="uniform", data=[0, 1], type=float) project.add_hyperparameter(name="axis_01", domain="uniform", data=[0, 1], type=float) project.add_hyperparameter(name="axis_02", domain="uniform", data=[0, 1], type=float) project.add_hyperparameter(name="axis_03", domain="uniform", data=[0, 1], type=float) project.add_hyperparameter(name="axis_04", domain="uniform", data=[0, 1], type=float) vfunc = FunctionSimulator() vfunc.load_default(vfunc_id) minima = vfunc.minima() def my_loss_function(data, params): return vfunc(**params) blackbox = BlackboxFunction(data=[], blackbox_func=my_loss_function) results = {} results["gt"] = [] for mini in minima: results["gt"].append(np.median(mini[0])) for iter in iterations: results[iter] = { "minima": {}, "distance": {}, "duration": None, "set_difference": None, "loss": None, "loss_history": {} } for i in range(vfunc.dims()): results[iter]["minima"]["axis_0{}".format(i)] = [] results[iter]["distance"]["axis_0{}".format(i)] = [] project.add_setting("max_iterations", iter) project.add_setting("solver", solver_name) solver = SolverPool.get(project=project) solver.blackbox = blackbox axis_minima = [] best_losses = [] best_sets_diff = [] for i in range(vfunc.dims()): axis_minima.append([]) loss_history = [] durations = [] for n in range(N): print("\rSolver={} iteration={} round={}".format(solver, iter, n), end="") start = time.time() solver.run(print_stats=False) end = time.time() durations.append(end - start) df, best = solver.get_results() loss_history.append(np.flip(np.sort(df['losses'].values))) best_row = df['losses'].idxmin() best_losses.append(df['losses'][best_row]) best_sets_diff.append( abs(df['axis_00'][best_row] - best['axis_00']) + abs(df['axis_01'][best_row] - best['axis_01']) + abs(df['axis_02'][best_row] - best['axis_02']) + abs(df['axis_03'][best_row] - best['axis_03']) + abs(df['axis_04'][best_row] - best['axis_04'])) for i in range(vfunc.dims()): tmp = df['axis_0{}'.format(i)][best_row] axis_minima[i].append(tmp) results[iter]["loss_history"] = loss_history for i in range(vfunc.dims()): results[iter]["minima"]["axis_0{}".format(i)] = [ np.mean(axis_minima[i]), np.std(axis_minima[i]) ] dist = np.sqrt((axis_minima[i] - results["gt"][i])**2) results[iter]["distance"]["axis_0{}".format(i)] = [ np.mean(dist), np.std(dist) ] results[iter]["loss"] = [np.mean(best_losses), np.std(best_losses)] results[iter]["set_difference"] = sum(best_sets_diff) results[iter]["duration"] = np.mean(durations) file = open(fname, 'wb') pickle.dump(results, file) file.close()