thursday/randomcube2.py

36 lines
1.1 KiB
Python
Raw Normal View History

from utils import phi
import numpy as np
def another_random_cube(objective, n_trials, n_dim, with_count, seed=None):
prng = np.random.default_rng(seed)
fopt = None
xopt = None
for i in range(n_trials):
x = prng.uniform(size=n_dim)
fx = objective(x)
if fopt is None or xopt is None or fx < fopt:
fopt = fx
xopt = x
return (fopt, xopt, n_trials) if with_count else (fopt, xopt)
def quasirandom_cube(objective, n_trials, n_dim, with_count):
# http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
magic = phi(n_dim)
alpha = np.zeros(n_dim)
for i in range(n_dim):
alpha[i] = pow(1 / magic, i + 1) % 1
xs = np.zeros((n_trials, n_dim))
xs[0, :] = 0.5 # first point is always dead center
for i in range(1, n_trials):
xs[i] = (xs[i - 1] + alpha) % 1
best_so_far = None
for i, x in zip(range(n_trials), xs):
fx = objective(x)
if best_so_far is None or fx < best_so_far[0]:
best_so_far = (fx, x)
fopt, xopt = best_so_far
return (fopt, xopt, n_trials) if with_count else (fopt, xopt)