Guest User

Untitled

a guest
Dec 2nd, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. from PIL import Image
  2. import numpy as np
  3. import random
  4. import sys
  5.  
  6.  
  7. def arraymutate(array, frequency, numpixels):
  8. """" Mutates given 2D-array with a specific frequency. In case of mutation, numpixels pixels get changed"""
  9. if random.random() <= frequency:
  10. # mutate numpixel times by flipping 0 to 1
  11. k = 0
  12. while k < numpixels:
  13. # generate random index and change 0 to 1 in that spot
  14. index1, index2 = random.randint(0, len(array)-1), random.randint(0, len(array[0])-1)
  15. if array[index1, index2] != 1:
  16. array[index1, index2] = 1
  17. k += 1
  18. return array
  19.  
  20. # We want to read in some images and modify them to create our training data. These are the labels for the pictures and the number of images of that type.
  21. shapes = [("back", 11), ("circ", 8), ("dash", 37), ("slash", 11), ("underscore", 9), ("vert", 32), ("blank", 1)]
  22. desiredoutput = {"back":"100000", "circ":"010000", "dash":"001000", "slash":"000100", "underscore":"000010", "vert":"000001", "blank":"000000"}
  23. dataUnchanged = []
  24.  
  25. # read in pre-defined images, convert them to 0/1 matrices and store them in a list
  26. for tupel in shapes:
  27. for i in range(0, tupel[1]):
  28. image = Image.open("{0}{1}.bmp".format(tupel[0], str(i))).convert("1")
  29. matrix = (np.reshape(list(image.getdata()), (8, 8)) / 255).astype(int)
  30. dataUnchanged.append((1 - matrix, desiredoutput[tupel[0]]))
  31.  
  32. trainingdata = []
  33. # desired number of examples in the training data set
  34. numberexamples = sys.argv[1]
  35. # desired frequency of mutation
  36. mutationfrequency = float(sys.argv[2])
  37. # number of pixels that get changed randomly
  38. pixelmutation = [1, 2, 3, 4]
  39.  
  40. # create a list of tupels with input patterns and desired output. The input patterns may get changed slighty via arraymutate function
  41.  
  42. for n in range(int(numberexamples)):
  43. example, pixelchanges = random.choice(dataUnchanged), random.choice(pixelmutation)
  44. trainingdata.append((arraymutate(example[0], mutationfrequency, pixelchanges), example[1]))
  45. # print statement is just for debugging
  46. #print("currently doing training object number" + str(n))
  47.  
  48. with open("recog_input", "wb") as fp:
  49. np.save(fp, trainingdata)
Advertisement
Add Comment
Please, Sign In to add comment