Skip to content

Instantly share code, notes, and snippets.

@Dilaz
Created March 8, 2020 19:21
Show Gist options
  • Save Dilaz/395354387adb02a4beeb73fc280e3070 to your computer and use it in GitHub Desktop.
Save Dilaz/395354387adb02a4beeb73fc280e3070 to your computer and use it in GitHub Desktop.
import tensorflow as tf
def encode_input(num):
return [int(i) for i in tuple(bin(num)[2:].zfill(8))]
def encode_fizzbuzz(num):
if num % 3 == 0 and num % 5 == 0:
# Fizzbuzz
return [1, 0, 0, 0]
elif num % 3 == 0:
# Fizz
return [0, 1, 0, 0]
elif num % 5 == 0:
# Buzz
return [0, 0, 1, 0]
else:
# Number
return [0, 0, 0, 1]
def decode_fizzbuzz(result, num):
return ['FizzBuzz', 'Fizz', 'Buzz', num][max(range(len(result)), key=lambda x: result[x])]
def main():
x = []
y = []
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, input_dim=8, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(4, activation='softmax')
])
model.compile(tf.keras.optimizers.Adam(learning_rate=0.001),
loss='categorical_crossentropy')
for i in range(100):
x.append(encode_input(i))
y.append(encode_fizzbuzz(i))
print(x,y)
model.fit(x=x, y=y,
verbose=2, shuffle=True, epochs=1000)
correct = 0
wrong = 0
for i in range(1, 101):
result = model.predict([encode_input(i)])
output = decode_fizzbuzz(result[0], i)
print(output, end=' ')
if output == decode_fizzbuzz(encode_fizzbuzz(i), i):
correct += 1
else:
wrong += 1
print('')
print('Total correct:', correct)
print('Wrong:', wrong)
print('Correct percentage:', correct / (correct + wrong) * 100, '%')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment