<jupyter_start><jupyter_text>Solving FizzBuzz with Keras  Overview- This notebook provides an example Keras network to solve FizzBuzz.- This is a supervised classification problem, so we'll train our model on labeled data.  What is FizzBuzz?FizzBuzz is a common programming interview problem. Here's the setup.- Write a program that outputs all the integers from 1 to 100.- If the number is a multpile of 3, then output the string "Fizz"- If the number is a multiple of 5, then output the string "Buzz"- If the number is a multiple of 15, output the string "FizzBuzz"- For any other number, output that, number itself.<jupyter_code>import warnings
warnings.filterwarnings('ignore')

# imports
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
from keras.models import Model
# Specify the number of binary digits. 
NUM_DIGITS = 10
## Setup the training data for 101-1024. 1024 is the highest number countable with 10 binary digits
raw_training_data = np.array(range(101, 2**NUM_DIGITS))
## This is a numpy array of integers.
raw_training_data[0:20]
# We need to binary encode our inputs
def binary_encode(i, NUM_DIGITS):
    return np.array([i >> d & 1 for d in range(NUM_DIGITS)])
print(1, binary_encode(1, NUM_DIGITS))
print(2, binary_encode(2, NUM_DIGITS))
print(3, binary_encode(3, NUM_DIGITS))
print(4, binary_encode(4, NUM_DIGITS))

binary_encode(3, NUM_DIGITS)
print(256, binary_encode(256, NUM_DIGITS))
print(512, binary_encode(512, NUM_DIGITS))
print(1023, binary_encode(1023, NUM_DIGITS))
encoded_training_data = [binary_encode(i, NUM_DIGITS) for i in raw_training_data]
x_train = np.array(encoded_training_data)
x_train[0]
# List out the state space. What are the different states that the data could be in:
# there's only 4 options/states in the FizzBuzz setup
# A number is a multiple of 3 and 5, only 3, only 5, or it ain't
# Now we'll need to one hot encode the training data for y
def fizz_buzz_encode(i):
    if i % 15 == 0:
        return np.array([0, 0, 0, 1]) # encoding for "fizzbuzz"
    elif i % 5 == 0: 
        return np.array([0, 0, 1, 0]) # encoding for "buzz"
    elif i % 3  == 0: 
        return np.array([0, 1, 0, 0]) # encoding for "fizz"
    else:
        return np.array([1, 0, 0, 0]) # encoding for the number output
print("Return only the number", fizz_buzz_encode(1))
print("Multiple of 3", fizz_buzz_encode(3))
print("Multiple of 5", fizz_buzz_encode(5))
print("Return only the number", fizz_buzz_encode(7))
print("Multiple of both 3 and 5", fizz_buzz_encode(15))
# y_train is the encoded output. 
# This is our "labeled data" for supervised learning
y_train = np.array([fizz_buzz_encode(i) for i in range(101, 2 ** NUM_DIGITS)])
y_train
# Now let's build our model, add layers, compile, and fit it!
model = Sequential()
## Add the model's layers. 
model.add(Dense(1000, input_dim=NUM_DIGITS, activation="relu"))
model.add(Dense(1000, activation="relu"))
model.add(Dense(4, activation="softmax"))
# categorical cross entropy is the recommended loss function for 
# metrics is a good
model.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=["accuracy"])
model.fit(x_train, y_train, nb_epoch=10, batch_size=128)
# convert fizzbuzz to binary
def fizz_buzz(i, prediction):
    return [str(i), "fizz", "buzz", "fizzbuzz"][prediction]

# Setup x_test  fizzbuzz for prime numbers from 1 to 100
numbers = np.arange(1, 101)
x_test = np.transpose(binary_encode(numbers, NUM_DIGITS))
y_test = model.predict_classes(x_test)
# Setup predicted output
predictions = np.vectorize(fizz_buzz)(numbers, y_test)
print (predictions)
# correct answers for fizzbuzz on 1-100, these are our actual values
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)
# Let's evaluate the model's predictions
evaluate = np.array(answer == predictions)
print (np.count_nonzero(evaluate == True) / 100)
answer == predictions<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10814036762950585, 'fraction_numerical': 0.03318214370971592, 'mean_word_length': 4.827538247566064, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '455792', 'license': 'MIT', 'n_tokens_mistral': 1530, 'n_tokens_neox': 1369, 'n_words': 496, 'path': 'fizz_buzz_classifier.ipynb', 'repo_name': 'ljackson707/Deep_Learning', 'size': '4189'}