forked from miloharper/neural-network-animation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
79 lines (66 loc) · 3 KB
/
main.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from neural_network import NeuralNetwork
from formulae import calculate_average_error, seed_random_number_generator
from video import generate_writer, annotate_frame, take_still
import parameters
class TrainingExample():
def __init__(self, inputs, output):
self.inputs = inputs
self.output = output
if __name__ == "__main__":
# Seed the random number generator
seed_random_number_generator()
# Assemble a neural network, with 3 neurons in the first layer
# 4 neurons in the second layer and 1 neuron in the third layer
network = NeuralNetwork([3, 4, 1])
# Training set
examples = [TrainingExample([0, 0, 1], 0),
TrainingExample([0, 1, 1], 1),
TrainingExample([1, 0, 1], 1),
TrainingExample([0, 1, 0], 1),
TrainingExample([1, 0, 0], 1),
TrainingExample([1, 1, 1], 0),
TrainingExample([0, 0, 0], 0)]
# Create a video and image writer
fig, writer = generate_writer()
# Generate an image of the neural network before training
print "Generating an image of a new neural network"
network.do_not_think()
network.draw()
take_still("results/new_neural_network.png")
# Generate a video of the neural network learning
print "Generating a video of the neural network learning."
print "There will be " + str(len(examples) * len(parameters.show_iterations)) + " frames."
print "This may take a long time. Please wait..."
with writer.saving(fig, parameters.video_file_name, 100):
for i in range(1, parameters.training_iterations + 1):
cumulative_error = 0
for e, example in enumerate(examples):
cumulative_error += network.train(example)
if i in parameters.show_iterations:
network.draw()
annotate_frame(i, e, average_error, example)
writer.grab_frame()
average_error = calculate_average_error(cumulative_error, len(examples))
print "Success! Open the file " + parameters.video_file_name + " to view the video."
# Generate an image of the neural network after training
print "Generating an image of a trained neural network"
network.do_not_think()
network.draw()
take_still("results/trained_neural_network.png")
# Consider a new situation
while True:
print "Enter new input sequence"
new_input = raw_input()
new_input_list = [int(i) for i in new_input]
print "Considering a new situation " + str(new_input_list)
print "Prediction: ", network.think(new_input_list)
network.draw()
file_name = "results/neural_network_%s.png" % new_input
take_still(file_name)
print "Check out %s" % file_name
# Consider a new situation
# new_situation = [1, 1, 0]
# print "Considering a new situation " + str(new_situation) + "?"
# print network.think(new_situation)
# network.draw()
# take_still("neural_network_new_situation.png")