Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import ipdb
- import numpy as np
- from random import randint
- # My Hill Climbing
- def my_hillclimbing(fun, x0, bounds, maxiter, step, args):
- x = x0
- cost = fun(x,*args)
- best_cost = cost
- best_x = x
- xmin = []
- xmax = []
- for i in range(0,len(bounds)):
- xmin.append(bounds[i][0])
- xmax.append(bounds[i][1])
- iteration = 0
- for i in range(0,maxiter): #stop criterion
- #while (best_cost > 0.3 or iteration > maxiter):
- first = 1
- new_x = x.copy()
- while (first or (not (all(new_x>=xmin) and all(new_x<=xmax)))):
- new_x = x.copy()
- first = 0
- idx = randint(0,len(x)-1)
- signal = randint(0,1)
- new_x[idx] = new_x[idx]+(int(signal)*step)-(int(not(signal))*step)
- #print("trying new_x[%d] = %f" %(idx,new_x[idx]))
- new_cost = fun(new_x,*args)
- print ("new_x: %s \t new_cost: %s" % (new_x, new_cost))
- if new_cost <= best_cost:
- best_cost = new_cost
- best_x = new_x.copy()
- if (new_cost < cost):
- cost = new_cost
- x = new_x.copy()
- iteration += 1
- class list_results(object):
- def __init__(self):
- self.x = best_x
- self.cost = best_cost
- res = list_results()
- return (res);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement