forked from joelgrus/joelnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fizzbuzz.py
64 lines (51 loc) · 1.33 KB
/
fizzbuzz.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
FizzBuzz is the following problem:
For each of the numbers 1 to 100:
* if the number is divisible by 3, print "fizz"
* if the number is divisible by 5, print "buzz"
* if the number is divisible by 15, print "fizzbuzz"
* otherwise, just print the number
"""
from typing import List
import numpy as np
from joelnet.nn import NeuralNet
from joelnet.layers import Tanh
from joelnet.optim import SGD, Adam
def fizz_buzz_encode(x: int) -> List[int]:
if x % 15 == 0:
return [0, 0, 0, 1]
elif x % 5 == 0:
return [0, 0, 1, 0]
elif x % 3 == 0:
return [0, 1, 0, 0]
else:
return [1, 0, 0, 0]
def binary_encode(x: int) -> List[int]:
"""
10 digit binary encoding of x
"""
return [x >> i & 1 for i in range(10)]
inputs = np.array([
binary_encode(x)
for x in range(101, 1024)
])
targets = np.array([
fizz_buzz_encode(x)
for x in range(101, 1024)
])
net = NeuralNet(
hidden_layer_sizes=(50, ),
activation=Tanh,
input_size=10,
output_size=4
)
net.fit(
inputs,
targets,
optimizer=Adam())
for x in range(1, 101):
predicted = net.predict(binary_encode(x))
predicted_idx = np.argmax(predicted)
actual_idx = np.argmax(fizz_buzz_encode(x))
labels = [str(x), "fizz", "buzz", "fizzbuzz"]
print(x, labels[predicted_idx], labels[actual_idx])