Created
January 30, 2018 15:18
-
-
Save binaryfoundry/3bd4e3c1ee13b7e35f454689b0ef2fa1 to your computer and use it in GitHub Desktop.
Port of Joel Grus Fizz Buzz in Tensorflow to 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
from keras.models import Sequential | |
from keras.layers import Dense | |
import numpy as np | |
np.random.seed(7) | |
NUM_DIGITS = 12 | |
def binary_encode(i, num_digits): | |
return np.array([i >> d & 1 for d in range(num_digits)]) | |
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]) | |
def fizz_buzz(i, prediction): | |
return [str(i), "fizz", "buzz", "fizzbuzz"][prediction] | |
X = np.array([binary_encode(i, NUM_DIGITS) for i in range(101, 2 ** NUM_DIGITS)]) | |
Y = np.array([fizz_buzz_encode(i) for i in range(101, 2 ** NUM_DIGITS)]) | |
model = Sequential() | |
model.add(Dense(NUM_DIGITS, input_dim=NUM_DIGITS, activation='relu')) | |
model.add(Dense(100, activation='relu')) | |
model.add(Dense(4, activation='softmax')) | |
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) | |
model.fit(X, Y, epochs=2000, batch_size=128) | |
scores = model.evaluate(X, Y) | |
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) | |
numbers = np.arange(1, 101) | |
X2 = np.transpose(binary_encode(numbers, NUM_DIGITS)) | |
predictions = model.predict_classes(X2) | |
output = np.vectorize(fizz_buzz)(numbers, predictions) | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment