Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Port of Joel Grus Fizz Buzz in Tensorflow to Keras
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
You can’t perform that action at this time.