Created
February 11, 2017 12:44
-
-
Save shibuiwilliam/2d49efd5e1e95f4582aa5a55ea861af6 to your computer and use it in GitHub Desktop.
fizzbuzz in Keras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from keras.models import Sequential | |
from keras.layers import Dense | |
from keras.utils import np_utils | |
from keras.layers import Dense | |
from keras.models import Model | |
# create training data | |
def binary_encode(i, num_digits): | |
return np.array([i >> d & 1 for d in range(num_digits)]) | |
NUM_DIGITS = 10 | |
trX = np.array([binary_encode(i, NUM_DIGITS) for i in range(101, 2 ** NUM_DIGITS)]) | |
# fizzbuzz for training data | |
def fizz_buzz_encode(i): | |
if i % 15 == 0: return np.array([0, 0, 0, 1]) | |
elif i % 5 == 0: return np.array([0, 0, 1, 0]) | |
elif i % 3 == 0: return np.array([0, 1, 0, 0]) | |
else: return np.array([1, 0, 0, 0]) | |
trY = np.array([fizz_buzz_encode(i) for i in range(101, 2 ** NUM_DIGITS)]) | |
# model | |
model = Sequential() | |
model.add(Dense(1000, input_dim=10, activation="relu")) | |
model.add(Dense(1000, activation="relu")) | |
model.add(Dense(4, activation="softmax")) | |
model.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=["accuracy"]) | |
model.fit(trX, trY, nb_epoch=100, batch_size=128) | |
# fizzbuzz to binary | |
def fizz_buzz(i, prediction): | |
return [str(i), "fizz", "buzz", "fizzbuzz"][prediction] | |
# try fizzbuzz for prime numbers from 1 to 100 | |
numbers = np.arange(1, 101) | |
teX = np.transpose(binary_encode(numbers, NUM_DIGITS)) | |
teY = model.predict_classes(teX) | |
output = np.vectorize(fizz_buzz)(numbers, teY) | |
print (output) | |
# answer | |
answer = np.array([]) | |
for i in numbers: | |
if i % 15 == 0: answer = np.append(answer, "fizzbuzz") | |
elif i % 5 == 0: answer = np.append(answer, "buzz") | |
elif i % 3 == 0: answer = np.append(answer, "fizz") | |
else: answer = np.append(answer, str(i)) | |
print (answer) | |
# evaluate | |
evaluate = np.array(answer == output) | |
print (np.count_nonzero(evaluate == True) / 100) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment