home · contact · privacy
Add basic neural networking experiments.
[plomrogue2-experiments] / neural / simple_perceptron.py
1 def step(x):
2     step = 0  # If 0.5, we need no bias for AND and OR; if 0, none for NOT.
3               # With learning, the bias will slowly balance any choice.
4     if x >= step:
5         return 1
6     else:
7         return 0
8
9 def result(inputs):
10     s = 0
11     perceptron['inputs'] = inputs[:]
12     for i in range(len(inputs)):
13         s += inputs[i] * perceptron['weights'][i]
14     return step(s + perceptron['bias'])
15
16 # identity
17 #training_set = [((0,), 0),
18 #                ((1,), 1)]
19
20 # NOT
21 #training_set = [((0,), 1),
22 #                ((1,), 0)]
23
24 # AND
25 #training_set = [((0,0), 0),
26 #                ((1,0), 0),
27 #                ((0,1), 0),
28 #                ((1,1), 1)]
29
30 # OR
31 #training_set = [((0,0), 0),
32 #                ((1,0), 1),
33 #                ((0,1), 1),
34 #                ((1,1), 1)]
35
36 # NOT (with one irrelevant column)
37 #training_set = [((0,0), 1),
38 #                ((1,0), 0),
39 #                ((0,1), 1),
40 #                ((1,1), 0)]
41
42 # XOR (will fail, as Minsky/Papert say)
43 #training_set = [((0,0), 0),
44 #                ((1,0), 1),
45 #                ((0,1), 1),
46 #                ((1,1), 0)]
47
48 # 1 if above f(x)=x line, else 0
49 training_set = [((0,1), 1),
50                 ((2,3), 1),
51                 ((1,1), 0),
52                 ((2,2), 0)]
53
54 # 1 if above f(x)=x**2, else 0 (will fail: no linear separability)
55 #training_set = [((2,4), 0),
56 #                ((2,5), 1),
57 #                ((3,9), 0),
58 #                ((3,10), 1)]
59
60 perceptron = {'weights': [0 for i in range(len(training_set[0][0]))],
61               'bias': 0}
62 adaption_size = 0.1
63
64 for i in range(100):
65     print()
66     go_on = False
67     for element in training_set:
68         inputs = element[0]
69         target = element[1]
70         result_ = result(inputs)
71         print("inputs %s target %s result %s correctness %5s weights %s bias %s" % (inputs, target, result_, target==result_, perceptron['weights'], perceptron['bias']))
72         if target != result_:
73             go_on=True
74         perceptron['bias'] += adaption_size * (target - result_)
75         for i in range(len(perceptron['weights'])):
76             perceptron['weights'][i] += adaption_size * (target - result_) * perceptron['inputs'][i]
77     if not go_on:
78         break
79 print()
80 if go_on:
81     print('COULD NOT SOLVE.')
82 else:
83     print('SUCCESS')