forked from nguyensmai/cumule
/
silent_predictor.py
623 lines (466 loc) · 19.1 KB
/
silent_predictor.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
import pylab,pickle,sys,pprint,random,time,math
from collections import deque
import numpy as np
from numpy.random import RandomState
import pickle
from copy import copy,deepcopy
from matplotlib.pyplot import *
import argparse
import sys
#FFNN supervised learning packages
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.tools.shortcuts import buildNetwork
from pybrain.datasets import SupervisedDataSet
from pybrain.structure import TanhLayer, LinearLayer
from pybrain.tools.validation import ModuleValidator
#5th January 2014. Cumule Algorithm (Chrisantha Fernando)
PHASE_1_LENGTH = 100000
# EVOLUTION_PERIOD = 2 #Evolve predictors every 10 episodes.
WEIGHT_DECAY=0.1
# MUTATE_MASK_PROBABILITY = 0.9
BACKTIME=10
PREDICTOR_MUTATION_PROBABILITY=0.8
# WEIGHT_COPY_PROBABILITY=0.05
parser = argparse.ArgumentParser()
parser.add_argument("timelimit",default=50,type=int)
parser.add_argument("-n","--num_predictors",help="population size(default:50)",default=50,type=int)
parser.add_argument("--runs",help="number of runs(default:1)",default=1,type=int)
parser.add_argument("--epochs",help="number of epochs for each training(default:5)",default=5,type=int)
parser.add_argument("-ts","--test_set_length",help="test set length(default:50)",default=50,type=int)
parser.add_argument("-e","--evolution_period", help="evolution period(default:10)", type=int, default=10)
parser.add_argument("-a","--archive_threshold", help="threshold for getting into the archive(default: 0.02)", type=float, default=0.02)
parser.add_argument("-lr","--learning_rate", help="learning rate for predictors(default: 0.01)", type=float, default=0.01)
parser.add_argument("-r","--replication", help="enable weights replication(default: no)",action="store_true", default=False)
parser.add_argument("-lg","--logfile", help="log file name(default: prediction.log)",type=str, default="prediction.log")
parser.add_argument("-i","--mutate_input", help="enable input mask mutation(default: yes)",action="store_true", default=True)
parser.add_argument("--episode_length", help="number of samples per episode(default: 50)",action="store_true", default=10)
parser.add_argument("--show_test_error", help="test archive and show the plot", action="store_true",default=False)
parser.add_argument("--show_plots", help="show live plots", action="store_true",default=False)
parser.add_argument("--sliding_training", help="use sliding window of examples", action="store_true",default=False)
parser.add_argument("--input_mutation_prob", help="input mutation probability per bit(default: 0.05)", type=float, default=0.05)
parser.add_argument("--output_mutation_prob", help="output mutation probability per mask(default: 0.9)", type=float, default=0.9)
parser.add_argument("--replication_prob", help="weight copy probability per weight(default: 0.1)", type=float, default=0.1)
parser.add_argument("--predictor_mutation_prob", help="tournament loser mutation probability(default: 1)", type=float, default=1.0)
from world import World
class Predictor():
def __init__(self, inSize, outSize, LearningRate):
self.learning_rate = LearningRate
self.ds = SupervisedDataSet(inSize, outSize)
self.net = buildNetwork(inSize, 10, outSize, hiddenclass=TanhLayer, bias=True)
self.trainer = BackpropTrainer(self.net, self.ds, learningrate=self.learning_rate, verbose = False, weightdecay=WEIGHT_DECAY)
self.prediction = [0] * outSize
self.mse = 100
self.age=0
#Specific to Mai's code. Make input and output masks.
self.inputMask = [1 for i in range(inSize)]
# self.outputMask = [random.randint(0, 1) for i in range(outSize)]
self.outputMask = [0]*outSize
r = random.randint(0,outSize-1)
self.outputMask[r] = 1
self.error = 0
self.errorHistory = []
self.dErrorHistory = []
self.slidingError = 0
self.dError = 0
self.fitness = 0
self.problem=r
self.previousData=[]
def getPrediction(self, input):
out = self.net.activate(input)
return out
def trainPredictor(self):
self.age+=1
new_ds=deepcopy(self.ds)
if FLAGS.sliding_training:
if len(self.previousData)!=0:
for sample,target in self.previousData:
new_ds.addSample(sample,target)
self.trainer.setData(new_ds)
for i in range(FLAGS.epochs):
e = self.trainer.train()
if FLAGS.sliding_training:
self.previousData=deepcopy(self.ds)
#Update possible fitness indicators.
#Error now
self.error = e
#Entire error history
if len(self.errorHistory) < 5:
self.errorHistory.append(e)
else:
for i in range(len(self.errorHistory)-1):
self.errorHistory[i] = self.errorHistory[i+1]
self.errorHistory[-1] = e
#Sliding window error over appeox last 10 episodes characturistic time.
self.slidingError = self.slidingError*0.9 + self.error
#Instantaneous difference in last er ror between episodes.
if len(self.errorHistory) > 1:
self.dError = self.errorHistory[-1] - self.errorHistory[-2]
return e
def getFitness(self, type):
fit = 0
#Fitness function 1 Chrisantha's attempt
if type == 0:#SIMPLE MINIMIZE PREDICTION ERROR FITNESS FUNCTION FOR PREDICTORS.
# fit = -self.dError/(1.0*self.error)
fit = -self.error
elif type == 1:
#Fitness function 2 Mai's attempt (probably need to use adaptive thresholds for this to be ok)
if self.error > ERROR_THRESHOLD and self.dError > DERROR_THRESHOLD:
fit = 0
else:
fit = 1
self.fitness = fit
return fit
def storeDataPoint(self, inputA, targetA):
self.ds.addSample(inputA, targetA)
def predict(self,inputA):
return self.net.activate(inputA)
class Agent():
def __init__(self):
#The agent has a population of M predictors.
self.predictors = []
self.archive=[0 for i in range(World.state_size)]
for i in range(FLAGS.num_predictors):
p=Predictor(World.state_size + World.action_size,World.state_size, FLAGS.learning_rate)
self.predictors.append(p)
def problemsDistribution(self):
r=[[] for i in range(World.state_size)]
for predictor in self.predictors:
r[predictor.problem].append(predictor)
return r
def averageErrors(self,distr):
r=[]
for problem, predictors in enumerate(distr):
error=np.mean([p.error for p in predictors])
r.append(error)
return r
def minimumErrors(self,distr):
r=[]
for problem, predictors in enumerate(distr):
if len(predictors)>0:
error=min([p.error for p in predictors])
else:
error=5
r.append(error)
return r
def bestSolved(self,distr):
min_error=10000000000
best_solved=-1
best_predictor=-1
for problem, predictors in enumerate(distr):
if len(predictors)!=0:
errors=[p.error for p in predictors]
best=np.argmin(errors)
err=errors[best]
if err<min_error:
best_solved=problem
min_error=err
best_predictor=predictors[best]
return (best_solved,min_error,best_predictor)
def bestSolvingSpeed(self,distr):
min_speed=100000000
fastest=-1
for problem, predictors in enumerate(distr):
if len(predictors)!=0:
speed=min([p.dError for p in predictors])
if speed<min_speed and speed<0:
fastest=problem
min_speed=speed
return (fastest,min_speed)
# execute this AFTER storing into archive and BEFORE new training
def problemsMutationProbabilities(self,distr):
r=[]
min_err=1000000
max_err=-1000000
for problem, predictors in enumerate(distr):
if len(predictors)!=0:
err=np.mean([p.error for p in predictors])
else:
err=-1
if self.archive[problem]!=0:
err=err*2 # we discourage agent from generating predictors that solve already solved problems
if err>0 and err<min_err:
min_err=err
if err>0 and err>max_err:
max_err=err
r.append(err)
for k,v in enumerate(r):
if self.archive[k]==0:
r[k]=max_err*5
if v<0:
r[k]=max_err*3
r=np.divide(r,sum(r))
return r
def minErrors(self,distr):
r=[]
for problem, predictors in enumerate(distr):
if len(predictors)!=0:
errors=[p.error for p in predictors]
best=np.argmin(errors)
err=errors[best]
r.append((problem,err,predictors[best]))
return r
def problemsAllocation(self,distr):
return [len(predictors) for predictors in distr]
def getRandomMotor(self):
return [random.uniform(0,1), random.uniform(0,1)]
def storeDataPoint(self, inp, targ):
for i in range(FLAGS.num_predictors):
#APPLY INPUT AND OUTPUT MASKS BEFORE SENDING DATA TO PREDICTORS.
inputA = [0]*len(inp)
for j in range(len(inp)):
inputA[j] = inp[j]*self.predictors[i].inputMask[j]
target = [0]*len(targ)
for j in range(len(targ)):
target[j] = targ[j]*self.predictors[i].outputMask[j]
self.predictors[i].storeDataPoint(inputA, target)
def trainPredictors(self):
ep = []
for i in range(FLAGS.num_predictors):
e = self.predictors[i].trainPredictor()
ep.append(e)
return ep
def createPredictor(self,hiddenLayerSize,problem):
p=Predictor(World.state_size + World.action_size,World.state_size, FLAGS.learning_rate)
p.problem=problem
p.outputMask = [0]*World.state_size
p.outputMask[problem]=1
return p
def clearPredictorsData(self):
for i in range(FLAGS.num_predictors):
self.predictors[i].ds.clear()
def copyAndMutatePredictor(self, winner, loser,distribution):
newLoser = deepcopy(self.predictors[winner])
self.predictors[loser] = newLoser
self.predictors[loser].learning_rate = FLAGS.learning_rate
self.predictors[loser].ds = SupervisedDataSet(10, 8)
self.predictors[loser].net = buildNetwork(10,10,8, bias=True)
self.predictors[loser].trainer = BackpropTrainer(self.predictors[loser].net, self.predictors[loser].ds, learningrate=self.predictors[loser].learning_rate, verbose = False, weightdecay=WEIGHT_DECAY)
if FLAGS.replication:
for i in range(len(self.predictors[loser].net.params)):
if random.uniform(0,1)<FLAGS.replication_prob:
self.predictors[loser].net.params[i] = self.predictors[winner].net.params[i]
# self.predictors[loser].net._setParameters(self.predictors[loser].net.params) # why?
if FLAGS.mutate_input:
for i in range(len(self.predictors[loser].inputMask)):
if random.uniform(0,1) < FLAGS.input_mutation_prob:
if self.predictors[loser].inputMask[i] == 0:
self.predictors[loser].inputMask[i] = 1
else:
self.predictors[loser].inputMask[i] = 0
if random.uniform(0,1) < FLAGS.output_mutation_prob:
self.predictors[loser].outputMask = [0]*World.state_size
r = np.random.choice(range(World.state_size),p=distribution)
self.predictors[loser].outputMask[r] = 1
self.predictors[loser].problem=r
class Cumule():
def __init__(self):
self.world = World()
self.agent = Agent()
self.popFitHistory=np.ndarray((FLAGS.num_predictors,BACKTIME))*0
self.timestep=0
def plot_fitness(self,fig):
popFit = []
for i in range(FLAGS.num_predictors):
popFit.append(self.agent.predictors[i].fitness)
self.popFitHistory=np.roll(self.popFitHistory,-1,axis=1)
self.popFitHistory[:,BACKTIME-1]=popFit
fig.clear()
for i in range(FLAGS.num_predictors):
fig.plot(self.popFitHistory[i,:])
x=self.timestep-(self.timestep%BACKTIME)
x=range(x,self.timestep+(self.timestep%BACKTIME))
fig.xaxis.set_ticks(np.arange(0, BACKTIME, 2.0))
# fig.xaxis.set_ticklabels(x)
xlabel('generations')
ylabel('fitness')
def test_archive(self):
plots=np.ndarray((World.state_size,FLAGS.test_set_length,2))*0
#Generate random initial motor command between -1 and 1.
m = self.agent.getRandomMotor()
#Geneate initial state for this motor command, and all else zero.
s = self.world.updateState(m)
for t in range(FLAGS.test_set_length):#*********************************************
m = self.agent.getRandomMotor()
stp1 = self.world.updateState(m)
inp = np.concatenate((s,m), axis = 0)
s = stp1
for i in range(World.state_size):
predicted=self.agent.archive[i].predict(inp)
expected=stp1
plots[i,t]=[predicted[i], expected[i]]
figure()
for i in range(World.state_size):
subplot(4,2,i)
title("Problem #"+str(i))
plot(plots[i,:,:])
show()
def archive_error(self,test_length,dims):
m = self.agent.getRandomMotor()
s = self.world.updateState(m)
err=0
for t in range(test_length):#*********************************************
m = self.agent.getRandomMotor()
stp1 = self.world.updateState(m)
inp = np.concatenate((s,m), axis = 0)
s = stp1
predicted=np.ndarray(World.state_size)
expected=stp1
for i in dims:
predicted[i]=self.agent.archive[i].predict(inp)[i]
err+=(predicted[i]-expected[i])**2
return 0.5*err/test_length
def run(self):
logfile=open("prediction.log",'w',1)
errHis = []
m = self.agent.getRandomMotor()
s = self.world.updateState(m)
archive_changed=False
if FLAGS.show_plots:
f=figure(figsize=(15,10))
min_archive_error=1000
for i in range(PHASE_1_LENGTH):
self.timestep+=1
if self.timestep==FLAGS.timelimit+1 and FLAGS.timelimit!=-1:
if min_archive_error==1000:
return -1
else:
return min_archive_error
elif FLAGS.timelimit==-1 and min_archive_error!=1000:
return min_archive_error
logfile.write("Timestep:"+str(i)+"\n")
m = self.agent.getRandomMotor()
s = self.world.resetState(m)
# Archive evaluating
if self.agent.archive.count(0)==0:
if archive_changed==True:
new_error=self.archive_error(FLAGS.test_set_length, range(World.state_size))
if min_archive_error>new_error:
logfile.write("New achieved archive error: "+str(new_error)+"\n")
min_archive_error=new_error
archive_changed=False
distr=self.agent.problemsDistribution()
# Check if there's a candidate solution in population
if i!=0:
bestEfforts=self.agent.minErrors(distr)
for problem, error, predictor in bestEfforts:
if error<FLAGS.archive_threshold:
if self.agent.archive[problem]==0:
logfile.write("Problem "+str(problem)+" was successfully solved. Error: "+str(round(error,4))+"\n")
self.agent.archive[problem]=predictor
self.agent.predictors[self.agent.predictors.index(predictor)]=self.agent.createPredictor(10,problem)
archive_changed=True
else:
old_err=self.archive_error(FLAGS.test_set_length,[problem])
old_predictor=self.agent.archive[problem]
self.agent.archive[problem]=predictor
new_err=self.archive_error(FLAGS.test_set_length,[problem])
if new_err<old_err:
logfile.write("Problem "+str(problem)+" has a better solution. Archived test error: "+str(round(old_err,4))+". Better solution: "+str(round(new_err,4))+"\n")
self.agent.predictors[self.agent.predictors.index(predictor)]=self.agent.createPredictor(10,problem)
archive_changed=True
else:
logfile.write("Solution for "+str(problem)+" remains the same. Archived test error: "+str(round(old_err,4))+". Candidate solution: "+str(round(new_err,4))+"\n")
self.agent.archive[problem]=old_predictor
# training of predictors
for t in range(FLAGS.episode_length):#*********************************************
m = self.agent.getRandomMotor()
stp1 = self.world.updateState(m)
inp = np.concatenate((s,m), axis = 0)
self.agent.storeDataPoint(inp, stp1)
s = stp1
self.agent.trainPredictors()
self.agent.clearPredictorsData()
distr=self.agent.problemsDistribution()
errHis.append(self.agent.minimumErrors(distr))
if FLAGS.show_plots:
#Plot the raw errors of the predictors in the population
# fig=subplot(2,3,3)
# fig.clear()
# bar(np.arange(0,World.state_size),self.agent.problemsMutationProbabilities(self.agent.problemsDistribution()))
# xlabel("problem number")
# ylabel("mutation probabilty")
fig=subplot(2,3,1)
fig.clear()
title('Minimum errors on outputs')
plot(errHis[-BACKTIME:])
xlabel('episodes(last '+str(BACKTIME)+')')
ylabel('errors')
fig=subplot(2,3,2)
fig.clear()
title('Minimum errors on outputs')
plot(errHis)
xlabel('episodes(all time)')
ylabel('errors')
fig=subplot(2,3,4)
fig.clear()
title('Solved problems(blue means solved)')
barlist=bar(np.arange(0,World.state_size),[1 for k in self.agent.archive])
for k,v in enumerate(self.agent.archive):
if v==0:
color='r'
barlist[k].set_color(color)
xlabel('problem')
ylabel('archive')
fig=subplot(2,3,5)
fig.clear()
bar(np.arange(0,World.state_size),self.agent.problemsAllocation(self.agent.problemsDistribution()))
xlabel("Problem number")
ylabel("Predictors")
draw()
if i%FLAGS.evolution_period == 0:
a = random.randint(0, FLAGS.num_predictors-1)
b = random.randint(0, FLAGS.num_predictors-1)
while(a == b):
b = random.randint(0, FLAGS.num_predictors-1)
fit1 = self.agent.predictors[a].getFitness(0) #0 = Fitness type Chrisantha, 1 = Fitness type Mai
fit2 = self.agent.predictors[b].getFitness(0)
winner = None
loser = None
if fit1 > fit2:
winner = a
loser = b
else:
winner = b
loser = a
if random.uniform(0,1) < FLAGS.predictor_mutation_prob:
self.agent.copyAndMutatePredictor(winner, loser, self.agent.problemsMutationProbabilities(self.agent.problemsDistribution()))
# fig=subplot(5,2,1)
# self.plot_fitness(fig)
#Plot which outputs are being predicted by each predictor, and what the errors are.
# outputTypes = []
# for i in range(FLAGS.num_predictors):
# outputTypes.append(self.agent.predictors[i].outputMask)
# fig=subplot(5,2,3)
# fig.clear()
# # imshow(np.array(outputTypes).T)
# bar(np.arange(0,World.state_size),self.agent.problemsAllocation(self.agent.problemsDistribution()))
# xlabel("Problem number")
# ylabel("Predictors")
logfile.close()
if __name__ == '__main__':
ion()
FLAGS=parser.parse_args()
fl=vars(FLAGS)
for k in sorted(fl.iterkeys()):
print k+": "+str(fl[k])
avg=0.0
errs=[]
for i in range(FLAGS.runs):
c = Cumule()
result=c.run()
tries=0
while result==-1 and tries<10:
result=c.run() # we need to get those N runs
tries+=1
if result==-1:
print "Couldn't find a solution for one of the runs in "+str(tries)+" tries. Something is clearly wrong."
else:
errs.append(result)
print result
print "Average: "+str(np.mean(errs))
print "Standard deviation: "+str(np.std(errs))
print "Min: "+str(np.min(errs))
print "Max: "+str(np.max(errs))
if FLAGS.show_test_error:
c.test_archive()
raw_input("Press Enter to exit")