-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal.py
476 lines (391 loc) · 15.2 KB
/
local.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
"""
Implementations of local search functions for a generalized problem containing following functions -
--------
problem.getObjValue()
problem.getNeighbours()
problem.getRandomNeighbour()
problem.isBetter()
problem.getRandomState()
"""
# ------- Deterministic Algorithms ------- #
def hillClimbingSearch_S(problem, userInteraction, beQuiet):
"""
`'Steepest Direction Hill Climbing'`
Inputs:
-------
`problem`
A problem class with required functions
Output:
-------
`state`
The state returned after Steepest Hill Climbing
"""
currentState = problem.state
if not beQuiet:
problem.visualize(currentState)
# for visualization
problem.hVals.append(problem.getObjValue(currentState))
steps=0
while True:
if problem.isGlobalOptimum(currentState):
return steps, currentState
neighbours = problem.getNeighbours(currentState)
runningBest = currentState
for n in neighbours:
nObjVal = problem.getObjValue(n)
runningBestVal = problem.getObjValue(runningBest)
if problem.isBetter(nObjVal, runningBestVal):
runningBest = n
if runningBest is currentState:
# no neighbour is better, optimum reached
return steps, currentState
else:
# jump to best neighbour
currentState = runningBest
# for visualization later on
problem.hVals.append(problem.getObjValue(currentState))
steps+=1
if not beQuiet:
if userInteraction:
input("Press enter to continue ")
problem.visualize(currentState)
def tabuSearch(problem, tabuSize, maxSteps, userInteraction, beQuiet):
"""
`'Tabu Search'`
Inputs:
-------
`problem`
A problem class with required functions
`tabuSize` (optional)
Number of elements to be remembered in the Tabu Tenure
`maxSteps` (optional)
Maximum number of steps allowed. Default: -1 means keep going till an optimum.
Output:
-------
`state`
The state returned after Tabu Search
"""
currentState = problem.state
if not beQuiet:
problem.visualize(currentState)
tabuList = list()
tabuList.append(currentState)
steps = 0
bestYet = currentState
# for visualization
problem.hVals.append(problem.getObjValue(currentState))
while maxSteps == -1 or steps<maxSteps:
if problem.isGlobalOptimum(currentState):
return steps, currentState
neighbours = problem.getNeighbours(currentState)
i=0
runningBest = neighbours[0]
while runningBest in tabuList:
i+=1
if i==len(neighbours):
return steps, bestYet
runningBest = neighbours[i]
# reaching this point means there is atleast
# one neighbour that isn't in the tabuList
for n in neighbours:
runningBestVal = problem.getObjValue(runningBest)
nObjVal = problem.getObjValue(n)
if n not in tabuList and \
problem.isBetter(nObjVal, runningBestVal):
runningBest = n
# add it to the tabu list
tabuList.append(runningBest)
if len(tabuList) > tabuSize:
# if tabu list size exceeds, pop the oldest element
tabuList.pop(0)
# make the jump to the better neighbour
currentState = runningBest
currentVal = problem.getObjValue(currentState)
bestYetVal = problem.getObjValue(bestYet)
if problem.isBetter(currentVal, bestYetVal):
bestYet = currentState
# for visualization later on
problem.hVals.append(problem.getObjValue(currentState))
steps+=1
if not beQuiet:
if userInteraction:
input("Press enter to continue ")
problem.visualize(currentState)
return steps, bestYet
# ------- Stochastic Algorithms ------- #
def hillClimbingSearch_FC(problem, maxTrials, userInteraction, beQuiet):
"""
`'First-Choice Hill Climbing'`
Inputs
------
`problem`
A problem class with required functions
`maxTrials` (optional)
Number of random neighbours to try before giving up.
Output
------
`state`
The state returned after First-Choice Hill Climbing
"""
currentState = problem.state
if not beQuiet:
problem.visualize(currentState)
steps = 0
# for visualization
problem.hVals.append(problem.getObjValue(currentState))
while True:
currentObjVal = problem.getObjValue(currentState)
if problem.isGlobalOptimum(currentState):
return steps, currentState
trials = 0
betterState = None
while trials < maxTrials:
neighbour = problem.getRandomNeighbour(currentState)
nObjVal = problem.getObjValue(neighbour)
if problem.isBetter(nObjVal, currentObjVal):
betterState = neighbour
break
trials+=1
if betterState:
# jump to neighbour better than current state
currentState = betterState
# for visualization later on
problem.hVals.append(problem.getObjValue(currentState))
steps+=1
if not beQuiet:
if userInteraction:
input("Press enter to continue ")
problem.visualize(currentState)
else:
print(f"{maxTrials} trials for random neighbours exhausted. No better neighbour found.")
return steps, currentState
def hillClimbingSearch_RR(problem, p, maxSteps, userInteraction, beQuiet):
"""
`'Random-Restart Hill Climbing'`
Inputs
------
`problem`
A problem class with required functions
`p` (optional)
The probability of random restart
`maxSteps` (optional)
Maximum number of steps allowed. Default = 10,000
Output
------
`state`
The state returned after Random-Restart Hill Climbing
"""
import random
currentState = problem.state
if not beQuiet:
problem.visualize(currentState)
steps = 0
restarts=0
bestYet = currentState
# for visualization
problem.hVals.append(problem.getObjValue(currentState))
while steps<maxSteps:
if problem.isGlobalOptimum(currentState):
print(f"\nTotal random restarts done: {restarts}.")
return steps, bestYet
if random.random()>=p:
# make a greedy step
neighbours = problem.getNeighbours(currentState)
runningBest = currentState
for n in neighbours:
nObjVal = problem.getObjValue(n)
runningBestVal = problem.getObjValue(runningBest)
if problem.isBetter(nObjVal, runningBestVal):
runningBest = n
if runningBest is currentState:
# no neighbour is better, check against the bestYet
runningBestVal = problem.getObjValue(runningBest)
bestYetVal = problem.getObjValue(bestYet)
if problem.isBetter(runningBestVal, bestYetVal):
bestYet = runningBest
else:
# jump to best neighbour
currentState = runningBest
# for visualization later on
problem.hVals.append(problem.getObjValue(currentState))
if not beQuiet:
print("Greedy step taken.")
if userInteraction:
input("Press enter to continue ")
problem.visualize(currentState)
currentVal = problem.getObjValue(currentState)
bestYetVal = problem.getObjValue(bestYet)
if problem.isBetter(currentVal, bestYetVal):
bestYet = currentState
steps+=1
else:
# do a random restart
currentState = problem.getRandomState()
# for visualization later on
problem.hVals.append(problem.getObjValue(currentState))
if not beQuiet:
if userInteraction:
input("Press enter to continue ")
print("Random restart done.")
problem.visualize(currentState)
currentVal = problem.getObjValue(currentState)
bestYetVal = problem.getObjValue(bestYet)
if problem.isBetter(currentVal, bestYetVal):
bestYet = currentState
restarts+=1
steps+=1
# after running out of steps, return the best yet state
print(f"\n[INFO] Total number of random restarts done: {restarts}.")
return steps, bestYet
def tempSchedule(steps, maxSteps):
''' Returns the temperature depending on how many steps have been taken'''
temperature = max(0.01, min(1, 1 - float(steps)/maxSteps))
return temperature
def simulatedAnnealing(problem, maxSteps, userInteraction, beQuiet):
"""
`'Simulated Annealing'`
Inputs
------
`problem`
A problem class with required functions
`maxSteps`
The number of steps according to which the temperature schedule is created.
Output
------
`state`
The state returned after Simulated Annealing
"""
import random
from math import exp
currentState = problem.state
steps = 0
bestYet = currentState
# for visualization
problem.hVals.append(problem.getObjValue(currentState))
while steps<maxSteps:
if problem.isGlobalOptimum(currentState):
return steps, bestYet
temperature = tempSchedule(steps, maxSteps)
# print(temperature)
if temperature == 0:
return currentState
neighbour = problem.getRandomNeighbour(currentState)
changeInObj = problem.getObjValue(neighbour) - \
problem.getObjValue(currentState)
if changeInObj > 0:
# if the neighbour is better, jump
currentState = neighbour
if not beQuiet:
if userInteraction:
input("Press enter to continue ")
print("Greedy step taken.")
problem.visualize(currentState)
steps+=1
currentVal = problem.getObjValue(currentState)
bestYetVal = problem.getObjValue(bestYet)
if problem.isBetter(currentVal, bestYetVal):
bestYet = currentState
# for visualization later on
problem.hVals.append(problem.getObjValue(currentState))
else:
# if the neighbour is worse, jump with some probability
if random.random() < exp(-1*changeInObj/temperature):
currentState = neighbour
if not beQuiet:
if userInteraction:
input("Press enter to continue ")
print("Step in a worse direction taken.")
problem.visualize(currentState)
steps+=1
currentVal = problem.getObjValue(currentState)
bestYetVal = problem.getObjValue(bestYet)
if problem.isBetter(currentVal, bestYetVal):
bestYet = currentState
# for visualization later on
problem.hVals.append(problem.getObjValue(currentState))
return steps, bestYet
#--------------Continuous Domain----------------#
import math
def gradDescent(problem, maxIterations, stepSize, beQuiet):
'''
`'Batch Gradient Descent'`
Inputs
------
`problem`
A problem class with required functions
`maxIterations`
The number of iterations to run gradient descent for
`stepSize`
The stepSize factor to begin gradient descent with
Output
------
`bestWeights`
The optimized weights obtained using gradient descent
'''
currentWeights = problem.weights
loss = problem.getObjValue(currentWeights)
bestLoss = loss
# for visualization
problem.losses.append(loss)
# mantain a list of last five loss values to be able to modify
# the stepSize if descent is going very slowly or very quickly
lossSchedule = []
lossSchedule.append(loss)
i=0
if not beQuiet:
print(f"Iter:[{i}/{maxIterations}]\tLoss: {problem.getObjValue(currentWeights)}")
while i < maxIterations:
# get partial derivatives of the loss w.r.t. the weights
derivatives = problem.getDerivatives(currentWeights)
# update the values of the weights
currentWeights = problem.updateWeights(currentWeights, derivatives, stepSize)
i+=1
loss = problem.getObjValue(currentWeights)
lossSchedule.append(loss)
# for visualization
problem.losses.append(loss)
if loss < bestLoss:
# if the loss is the lowest yet
bestWeights = currentWeights
bestLoss = loss
if len(lossSchedule)>5:
# if size of loss schedule exceeds 5, remove the oldest loss value
lossSchedule.pop(0)
if lossSchedule[-1] > lossSchedule[-2]:
# if the loss is increasing reduce the step size factor by 10
stepSize /= 10
if not beQuiet:
print("Step size factor was reduced to 1/10th")
if not beQuiet:
print(f"Iter:[{i}/{maxIterations}]\t\tLoss: {loss}")
return bestWeights, bestLoss
# ---------------- END for now --------------------- #
# TODO: add the functions below
# def stochasticLocalBeamSearch(problem, k=10):
# initStates = set()
# while len(initStates) < 10:
# while True:
# genState = problem.getRandomState()
# if genState in initStates:
# continue
# else:
# initStates.add(genState)
# break
# for state in initStates:
# neighbours =
# def geneticAlgorithm(population, state, p=0.01):
# import random
# while Time is left or We get a superfit person:
# new_population = set()
# weights = [problem.getObjValue(element) for element in population]
# for i in range(len(population)):
# x = random.choice(population, weights=weights)
# y = random.choice(population, weights=weights)
# offSpring = Reproduce(x, y)
# # if random.random() < p:
# # offSpring = Mutate(offSpring)
# new_population.add(offSpring)
# population.append(list(new_population))
# # return the best in the current population
# for element in population:
# def stochasticGradientDescent(problem, ):