Advertisement
Guest User

TS_core01

a guest
Aug 13th, 2014
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. import random
  2. import matplotlib.pyplot
  3.  
  4. def matrixCreate(rows,columns):
  5. list = [[0 for x in xrange(columns)] for x in xrange(rows)]
  6. return list
  7.  
  8. def matrixRandomize(v):
  9. for row in range(len(v)):
  10. for column in range(len(v[row])):
  11. v[row][column] = random.random()
  12. return v
  13.  
  14. def fitness(v):
  15. total, average = 0.0,0.0
  16. for row in range(len(v)):
  17. for column in range(len(v[row])):
  18. total += v[row][column]
  19. average = total/(len(v)*len(v[row]))
  20. return average
  21.  
  22. def matrixPerturb(p, prob):
  23. c = matrixCreate(len(p),len(p[0]))
  24. for row in range(len(p)):
  25. for column in range(len(p[row])):
  26. c[row][column] = p[row][column]
  27. if prob > random.random():
  28. c[row][column] = random.random()
  29. return c
  30.  
  31. def plotVectorAsLine(fits):
  32. matplotlib.pyplot.plot(fits[0])
  33. matplotlib.pyplot.show()
  34. return
  35.  
  36. genes = matrixCreate(50, 5000)
  37. for i in range(5):
  38. parent = matrixCreate(1, 50)
  39. parent = matrixRandomize(parent)
  40. parentFitness = fitness(parent)
  41. fits = matrixCreate(1, 5000)
  42. for currentGeneration in range(5000):
  43. for j in range(50):
  44. genes[j][currentGeneration] = parent[0][j]
  45. print currentGeneration, parentFitness
  46. child = matrixPerturb(parent, 0.05)
  47. childFitness = fitness(child)
  48. fits[0][currentGeneration] = parentFitness
  49. if childFitness > parentFitness:
  50. parent = child
  51. parentFitness = childFitness
  52. #plotVectorAsLine(fits)
  53.  
  54. matplotlib.pyplot.imshow(genes, cmap=matplotlib.pyplot.cm.gray, aspect='auto', interpolation='nearest')
  55. matplotlib.pyplot.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement