Guest User

Untitled

a guest
May 20th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. import numpy as np
  2. from keras.models import Sequential
  3. from keras.layers import Dense
  4. from keras.utils.vis_utils import plot_model
  5.  
  6.  
  7. # binary representation of the number
  8. def binary_encode(i, num_digits):
  9. s = "{0:b}".format(i).zfill(num_digits)
  10. return np.array([int(x) for x in s])
  11.  
  12. # one hot encoding for even and odd labels
  13. def one_hot_encode(i):
  14. if i % 2 == 0:
  15. return np.array([1, 0]) # even label
  16. else:
  17. return np.array([0, 1]) # odd label
  18.  
  19. NUM_DIGITS = 10
  20. train_X = np.array([binary_encode(i, NUM_DIGITS) for i in range(101, 2 ** NUM_DIGITS)])
  21. train_Y = np.array([one_hot_encode(i) for i in range(101, 2 ** NUM_DIGITS)])
  22.  
  23.  
  24. # model
  25. model = Sequential()
  26. model.add(Dense(10, input_dim=10, activation="relu"))
  27. model.add(Dense(5, activation="relu"))
  28. model.add(Dense(2, activation="softmax"))
  29. plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)
  30. model.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=["accuracy"])
  31. model.fit(train_X, train_Y, nb_epoch=20, verbose=1)
  32.  
  33.  
  34. # one hot prediction to text
  35. def prediction_to_text(i, prediction):
  36. return ["even", "odd"][prediction]
  37.  
  38.  
  39. # try to predict even or odd for numbers from 1 to 100
  40. numbers = np.arange(1, 101)
  41. test_X = np.array([binary_encode(i, NUM_DIGITS) for i in numbers])
  42. test_Y = model.predict_classes(test_X)
  43. output = np.vectorize(prediction_to_text)(numbers, test_Y)
  44. #print('predicted', output)
  45.  
  46.  
  47. # correct answer
  48. answer = np.array([])
  49. for i in numbers:
  50. if i % 2 == 0:
  51. answer = np.append(answer, "even")
  52. else:
  53. answer = np.append(answer, "odd")
  54. #print('correct', answer)
  55.  
  56.  
  57. # evaluate
  58. evaluate = np.array(answer == output)
  59. print(np.count_nonzero(evaluate == True) / len(output))
Add Comment
Please, Sign In to add comment