[PYTHON] Try to solve the fizzbuzz problem with Keras

Solve the fizzbuzz problem with Keras

Do you know the Fizzbuzz problem? This is a beginner's problem in programming, and you write the following code.

An example of the answer is written in Python as follows.

import numpy as np
num = np.arange(1,101,1)
for i in num:
    if i % 15 == 0: print ("fizzbuzz")
    elif i % 5 == 0: print ("buzz")
    elif i % 3 == 0: print ("fizz")
    else: print (i)

There are innumerable ways to write code, but basically it is easy to write by dividing the case into for and if.

However! It is human nature that makes us want to solve these problems with deep learning. Moreover, there are some ancestors who have solved it even in Tensorflow (although it has not been solved (.ŏ﹏ŏ)). http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/

So, let's rewrite the above Tensorflow fizzbuzz with Keras. Mainly only the model part has been migrated to Keras, and the other code is mostly based on the Tensorflow version as it is.

Target

A neural network model is created by supervised learning, and the correct answer rate of the model is evaluated using an integer from 1 to 100 as test data.

Write in Keras

Let's write it now.

First, import the required library.

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

Teacher data is required. This time, we will use integers from 101 to 1024 as teacher data, but we will have the teacher data in binary format. That is, the matrix at (923, 10) is the teacher 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)])

Now, we also need the fizzbuzz value for the teacher data. This is also made in binary format.

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)])

You now have an integer (binary format) from 101 to 1024 for teacher data and its fizzbuzz (binary format). Preparations are complete. Now let's write a model.

Generate models sequentially.

model = Sequential()

Add a layer. This time, we will use a 3-layer (fully combined) network.

model.add(Dense(1000, input_dim=10, activation="relu"))
model.add(Dense(1000, activation="relu"))
model.add(Dense(4, activation="softmax"))

The final output is an integer, fizz, buzz, or fizzbuzz, so the last layer will have an output of 4.

The optimization algorithm should be adagrad. The Tensorflow version was SGD, but it didn't converge much when I did it with Keras. Let's compile and train the model.

model.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=["accuracy"])
model.fit(trX, trY, nb_epoch=100, batch_size=128)

2017-02-06_fizzbuzz.PNG

It's a fair rate of convergence. (Slightly overfit?)

Model evaluation

Let's evaluate this model. Let's apply the model to integers from 1 to 100.

def fizz_buzz(i, prediction):
    return [str(i), "fizz", "buzz", "fizzbuzz"][prediction]
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)

came out.

2017-02-06_fizzbuzz2.PNG

By the way, the correct answer is as follows.

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)

2017-02-06_fizzbuzz3.PNG

Let's see the accuracy rate of the model.

evaluate = np.array(answer == output)
print (np.count_nonzero(evaluate == True) / 100)

2017-02-06_fizzbuzz4.PNG

97%!! Is it so good?

You may get a better accuracy rate by increasing the number of layers and units, but that's okay.

The whole code is below.

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


#Teacher data generation
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)])


#Teacher data fizzbuzz
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)


#Binary fizzbuzz conversion
def fizz_buzz(i, prediction):
    return [str(i), "fizz", "buzz", "fizzbuzz"][prediction]


#Try applying the model to integers 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)


#Correct 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)


#Correct answer rate
evaluate = np.array(answer == output)
print (np.count_nonzero(evaluate == True) / 100)

Recommended Posts

Try to solve the fizzbuzz problem with Keras
Try to solve the internship assignment problem with Python
Try to solve the N Queens problem with SA of PyQUBO
Try to solve the Python class inheritance problem
Try to solve the man-machine chart with Python
Try to solve the traveling salesman problem with a genetic algorithm (Theory)
Try to solve the programming challenge book with python3
[Python] Try to read the cool answer to the FizzBuzz problem
The first algorithm to learn with Python: FizzBuzz problem
I tried to solve the problem with Python Vol.1
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
Try to solve the traveling salesman problem with a genetic algorithm (execution result)
Stack problem: Try to solve "20. Valid Parentheses"
How to solve the bin packing problem
Solve the traveling salesman problem with OR-Tools
I wanted to solve the ABC164 A ~ D problem with Python
Try to solve the shortest path with Python + NetworkX + social data
Try to solve the function minimization problem using particle swarm optimization
The 16th offline real-time how to write reference problem to solve with Python
How to try the friends-of-friends algorithm with pyfof
The 19th offline real-time how to write reference problem to solve with Python
Try to solve a set problem of high school math with Python
Try creating a FizzBuzz problem with a shell program
Try to solve the problems / problems of "Matrix Programmer" (Chapter 1)
Try to visualize the room with Raspberry Pi, part 1
I tried to solve the soma cube with python
Try to get the contents of Word with Golang
[Neo4J] ④ Try to handle the graph structure with Cypher
Try to specify the axis with PyTorch's Softmax function
Try to factorial with recursion
Solve the Monty Hall problem
I tried to solve the virtual machine placement optimization problem (simple version) with blueqat
The 15th offline real-time I tried to solve the problem of how to write with python
CNN with keras Try it with the image you picked up
Try to play with the uprobe that supports Systemtap directly
I wanted to solve the Panasonic Programming Contest 2020 with Python
Finding a solution to the N-Queen problem with a genetic algorithm (2)
I tried to solve a combination optimization problem with Qiskit
Try to solve the problems / problems of "Matrix Programmer" (Chapter 0 Functions)
Try to automate the operation of network devices with Python
A story about how to deal with the CORS problem
The problem becomes easier to solve depending on the formulation method
Try to decipher the garbled attachment file name with Python
Finding a solution to the N-Queen problem with a genetic algorithm (1)
Try to extract the features of the sensor data with CNN
How to write offline real time I tried to solve the problem of F02 with Python
Try to operate Facebook with Python
Try to profile with ONNX Runtime
Try to introduce the theme to Pelican
Beginner RNN (LSTM) | Try with Keras
Cython to try in the shortest
Try blurring the image with opencv2
Try to output audio with M5STACK
The fastest way to try EfficientNet
The easiest way to try PyQtGraph
I tried to solve the ant book beginner's edition with python
Solve the initial value problem of ordinary differential equations with JModelica
Solve the Python knapsack problem with a branch and bound method
I tried to solve the shift scheduling problem by various methods
From "drawing" to "writing" the configuration diagram: Try drawing the AWS configuration diagram with Diagrams
Solve the subset sum problem with a full search in Python