Advertisement
toweber

my_optimization

Sep 12th, 2022
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. import os
  2. import ipdb
  3. import numpy as np
  4. from random import randint
  5.  
  6. # My Hill Climbing
  7. def my_hillclimbing(fun, x0, bounds, maxiter, step, args):
  8.      x = x0
  9.      cost = fun(x,*args)      
  10.      best_cost = cost
  11.      best_x = x
  12.  
  13.      xmin = []
  14.      xmax = []
  15.      for i in range(0,len(bounds)):
  16.           xmin.append(bounds[i][0])
  17.           xmax.append(bounds[i][1])
  18.  
  19.      iteration = 0
  20.      for i in range(0,maxiter):  #stop criterion
  21.      #while (best_cost > 0.3 or iteration > maxiter):
  22.           first = 1
  23.           new_x = x.copy()
  24.           while (first or (not (all(new_x>=xmin) and all(new_x<=xmax)))):
  25.                new_x = x.copy()
  26.                first = 0
  27.                idx = randint(0,len(x)-1)
  28.                signal = randint(0,1)
  29.                new_x[idx] = new_x[idx]+(int(signal)*step)-(int(not(signal))*step)
  30.                #print("trying new_x[%d] = %f" %(idx,new_x[idx]))
  31.  
  32.           new_cost = fun(new_x,*args)
  33.           print ("new_x: %s \t new_cost: %s" % (new_x, new_cost))
  34.           if new_cost <= best_cost:
  35.                best_cost = new_cost
  36.                best_x = new_x.copy()
  37.  
  38.           if (new_cost < cost):
  39.                cost = new_cost
  40.                x = new_x.copy()
  41.  
  42.           iteration += 1
  43.  
  44.      class list_results(object):
  45.           def __init__(self):
  46.                self.x = best_x
  47.                self.cost = best_cost
  48.  
  49.      res = list_results()
  50.  
  51.      return (res);
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement