-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perceptron.py
82 lines (56 loc) · 2 KB
/
Perceptron.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
79
80
import random
import nn_util
class Perceptron:
parameters = []
param_weights = []
outputs = []
weight_max = 0.0
param_len = 0
output_len = 0
learning_interval = 0.0
def __init__(self, plen, olen, weight_max=1, learning_interval=.1):
self.param_len = plen
self.output_len = olen
self.weight_max = weight_max
self.learning_interval = learning_interval
#calc random weights
for i in range(0, plen):
self.param_weights.append(random.uniform(0, weight_max))
def train(self, train_inputs, train_target):
total_input = 0.0
#calculate input
for i in range(0, len(train_inputs)):
total_input += train_inputs[i] * self.param_weights[i]
#sigmoid function to output
activated_input = nn_util.tobin(total_input)
#calc error
error = activated_input - train_target
#re-weight
for i in range(0, len(self.param_weights)):
self.param_weights[i] -= error * self.learning_interval * train_inputs[i]
def train_reps(self, reps):
for i in range(1, reps):
x = random.randint(-20, 20)
y = random.randint(-20, 20)
if y > x:
target = 1
else:
target = 0
tinputs = [x, y]
self.train(tinputs, target)
self.print_weights()
def test(self, test_inputs):
total_input = 0.0
#calculate input
for i in range(0, len(test_inputs)):
total_input += test_inputs[i] * self.param_weights[i]
#sigmoid function to output
activated_input = nn_util.sigmoid(total_input)
for i in range(0, len(test_inputs)):
print("input" + str(i) + ": " + str(test_inputs[i]))
print ("output: " + str(activated_input))
def print_weights(self):
index = 0
for weight in self.param_weights:
print(str(index) + ": " + str(weight))
index += 1