def runSingleSplit_pycma(fid, dim, iids=[1, 2, 3, 4, 5], num_reps=5):
    """
        Function running single-split CMA-ES.

        :param fid: The function id (from bbob)
        :param dim: The dimension to run the bbob-problem in
        :param rep1: The configuration to run before the splitpoint
        :param rep2: The configuration to run after the splitpoint
        :param split_idx: The splitpoint-index at which to switch between rep1 and rep2
        :param iids: The instances of the bbob-function to run
        :param num_reps: The amount of repetitions to run
        :return: The ERT over all num_reps runs on all instances in iids
    """
    obs = create_observer("Pycma", None, None)
    suite = cocoex.Suite("bbob", "", f"dimensions:{dim}")
    HittingTimes = []
    for i, iid in enumerate(iids):
        for j in range(num_reps):
            fitness_function = suite.get_problem_by_function_dimension_instance(
                fid, dim, iid)
            fitness_function.observe_with(obs)
            f = fitnessFunc(fitness_function)
            cma = CMAEvolutionStrategy([0] * 5, 0.5)
            cma.optimize(f)
            HittingTimes.append(cma.result.evaluations)
            print(cma.result.xbest)
            fitness_function.free()
    return np.mean(HittingTimes)
 def create_optimizer(self):
     from cma import CMAEvolutionStrategy
     opts = {'bounds': self.bounds}
     stddevs = (self.param_space.param_uppers - self.param_space.
                param_lowers) * self.stddev + self.param_space.param_lowers
     optimizer = CMAEvolutionStrategy(self.init_guess,
                                      np.amin(stddevs),
                                      inopts=opts)
     _ = optimizer.optimize(self._priv_evaluator)
     self.is_converged = True
Example #3
0
    def otimizar(self):
        lw = [0.0, 0.0, 0.0]
        up = [1.0, 1.0, 1.0]
        x0 = 3 * [0.1]
        sigma = 0.25

        # Otimizando
        c = CMAEvolutionStrategy(x0, sigma, {'bounds': [lw, up]})
        self.iniciar_tempo()
        c.optimize(self.func_objetivo, iterations=self.num_chamadas)
        self.finalizar_tempo()

        # Extraindo os melhores hiperparametros
        C_ = 2 ** (-5 + c.best.x[0] * 20)
        gamma_ = 2 ** (-15 + c.best.x[1] * 18)
        epsilon_ = abs(c.best.x[2])

        # Treinando SVM final com os parĂ¢metros encontrados
        self.svm = SVM(gamma_, C_, epsilon_)
        self.svm.treinar(self.X_treinamento, self.Y_treinamento)
        self.svm.testar(self.X_teste, self.Y_teste)
Example #4
0
def example_cma():
    def yangs4(x):
        # f = (a-b).c
        a = np.sum(np.square(np.sin(x)))
        b = np.exp(-np.sum(np.square(x)))
        c = np.exp(-np.sum(np.square(np.sin(np.sqrt(np.abs(x))))))
        return (a - b) * c

    n = 5
    x0 = n * [0.1]
    sigma0 = 0.1
    # evolution strategy
    es = CMAEvolutionStrategy(x0, sigma0)
    optSol = es.optimize(yangs4)
Example #5
0
def cma(fun, budget):
    sigma0 = 0.02
    range_ = fun.upper_bounds - fun.lower_bounds
    center = fun.lower_bounds + range_ / 2
    x0 = center
    options = dict(scaling=range_ / range_[0],
                   maxfevals=budget,
                   verb_log=0,
                   verb_disp=1,
                   verbose=1)
    es = CMAEvolutionStrategy(x0, sigma0 * range_[0], options)
    res = es.optimize(fun).result()
    xbest, ybest, nbeval, *rest = res
    return xbest, ybest, nbeval
Example #6
0
def main():

    bias0 = [0.0, -3.0] * total_biases
    weight0 = [0.0, -3.0] * total_weights
    x0 = bias0
    x0.extend(weight0)

    # assert(len(x0) == 108)
    sigma0 = 0.1

    # evolution strategy
    es = CMAEvolutionStrategy(x0, sigma0)
    optSol = es.optimize(regression_problem)
    print(optSol)

    sol = [-3.18979598e-02,  1.21945777e+00,  3.80408518e-02,
            7.99747577e-01,  9.51714572e-02,  8.10528673e-01, -5.97132372e-02,
            1.04204663e+00,  1.74305244e-02,  9.93532532e-01, -8.67464165e-02,
            9.51615254e-01, -3.77311791e-02,  9.97444596e-01, -5.84591048e-03,
            1.08793924e+00, -5.59697903e-02,  9.51347690e-01,  3.33323542e-02,
            1.00693954e+00]
Example #7
0
  def attack(self, image, target_class, limit):
    """
    TODO: Write Comment
    """
    bounds, initial = self.get_bounds(image, limit)

    def predict_fn(xs):
      return self.predict_classes(xs, image, target_class)

    def callback_fn(x, convergence=None):

      if self.es == 0:
        if self.attack_success(x.result[0], image, target_class):
          raise Exception(
              'Attack Completed :) Earlier than expected')
      else:
        return self.attack_success(x, image, target_class)

    if self.es == 0:

      opts = CMAOptions()

      if not self.verbose:
        opts.set('verbose', -9)
        opts.set('verb_disp', 40000)
        opts.set('verb_log', 40000)
        opts.set('verb_time', False)

      opts.set('bounds', bounds)

      if self.type_attack == 0:
        std = 63
      else:
        std = limit

      es = CMAEvolutionStrategy(initial, std / 4, opts)

      try:
        es.optimize(
            predict_fn,
            maxfun=max(
                1,
                400 //
                len(bounds)) *
            len(bounds) *
            100,
            callback=callback_fn)
      except Exception as e:
        if self.verbose:
          print(e)
        pass

      adv_x = es.result[0]

    else:

      es = differential_evolution(
          predict_fn,
          bounds,
          disp=self.verbose,
          maxiter=100,
          popsize=max(
              1,
              400 // len(bounds)),
          recombination=1,
          atol=-1,
          callback=callback_fn,
          polish=False)
      adv_x = es.x

    if self.attack_success(adv_x, image, target_class):
      return True, self.perturb_image(adv_x, image)[0]
    else:
      return False, image