-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfizzbuzz.py
62 lines (52 loc) · 1.4 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
"""
FizzBuzz is the following problem:
For each oh 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
"""
import numpy as np
from typing import List
from vsdl.train import train
from vsdl.nn import NeuralNet
from vsdl.layers import Linear, Tanh
from vsdl.optim import SGD
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 digits 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([
Linear(input_size=10, output_size=50),
Tanh(),
Linear(input_size=50, output_size=4)
])
train(net,
inputs,
targets,
num_epochs=5000,
optimizer=SGD(lr=0.001))
for x in range(1, 101):
predicted = net.forward(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])