-
Notifications
You must be signed in to change notification settings - Fork 0
/
neural_network.py
60 lines (52 loc) · 1.15 KB
/
neural_network.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
from random import random
class Perceptron():
"""docstring for Perceptron"""
def __init__(self, n):
self.weights = []
self.learn_const = 0.01
for i in range(0,n):
self.weights.append(random()*2-1)
def feedforward(self, inputs):
sum = 0.0
for i, e in enumerate(inputs):
sum += self.weights[i]*e
return self.activate(sum)
def activate(self, sum):
if(sum > 0):
return 1
else:
return -1
def train(self, inputs, desired):
guess = self.feedforward(inputs)
error = float(desired) - float(guess)
print(guess, error)
for i, e in enumerate(self.weights):
e += self.learn_const*error*inputs[i]
class Trainer():
"""docstring for Trainer"""
def __init__(self, x,y,a):
self.inputs = [x,y,1]
self.answer = a
def f(x):
return 2*x + 1
def findAns(x,y):
if(f(x)>y):
return 1
else:
return -1
def makeSamplePoints(n):
t = []
for e in range(0,n):
x = random()*200-100
y = random()*200-100
a = findAns(x,y)
t.append(Trainer(x,y,a))
return t
def trainPerc(p, t):
for e in t:
p.train(e.inputs, e.answer)
p = Perceptron(3)
t = makeSamplePoints(2000)
trainPerc(p,t)
print(p.feedforward([-10,0,1]))
print(p.feedforward([-10,0,1]))