Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import matplotlib.pyplot
- def matrixCreate(rows,columns):
- list = [[0 for x in xrange(columns)] for x in xrange(rows)]
- return list
- def matrixRandomize(v):
- for row in range(len(v)):
- for column in range(len(v[row])):
- v[row][column] = random.random()
- return v
- def fitness(v):
- total, average = 0.0,0.0
- for row in range(len(v)):
- for column in range(len(v[row])):
- total += v[row][column]
- average = total/(len(v)*len(v[row]))
- return average
- def matrixPerturb(p, prob):
- c = matrixCreate(len(p),len(p[0]))
- for row in range(len(p)):
- for column in range(len(p[row])):
- c[row][column] = p[row][column]
- if prob > random.random():
- c[row][column] = random.random()
- return c
- def plotVectorAsLine(fits):
- matplotlib.pyplot.plot(fits[0])
- matplotlib.pyplot.show()
- return
- genes = matrixCreate(50, 5000)
- for i in range(5):
- parent = matrixCreate(1, 50)
- parent = matrixRandomize(parent)
- parentFitness = fitness(parent)
- fits = matrixCreate(1, 5000)
- for currentGeneration in range(5000):
- for j in range(50):
- genes[j][currentGeneration] = parent[0][j]
- print currentGeneration, parentFitness
- child = matrixPerturb(parent, 0.05)
- childFitness = fitness(child)
- fits[0][currentGeneration] = parentFitness
- if childFitness > parentFitness:
- parent = child
- parentFitness = childFitness
- #plotVectorAsLine(fits)
- matplotlib.pyplot.imshow(genes, cmap=matplotlib.pyplot.cm.gray, aspect='auto', interpolation='nearest')
- matplotlib.pyplot.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement