1 """andgate using NeuralNetwork
2
3 for practical example, see [AndGateShell.py]
4 """
5
6 def f(x1,x2,w1,w2):
7 return x1*w1 + x2*w2
8
9 thres = 0.5
10 isOver=lambda x1,x2,w1,w2:f(x1,x2,w1,w2)>thres
11 result=isOver
12 isSame=lambda x1,x2,w1,w2,expected:result(x1,x2,w1,w2)==expected
13
14 def printGenerations(w1,w2):
15 testCase=((0,0),(0,1),(1,0),(1,1))
16 for eachX1,eachX2 in testCase:
17 print "(%d,%d) : %f"%(eachX1,eachX2,f(eachX1,eachX2,w1,w2))
18
19 def initialize():
20 pass
21
22
23 def everythingDone():
24 pass
25
26 def advanceGeneration():
27 pass
28
29 def printParameters():
30 pass
31
32 def calculateThisGeneration(w1,w2):
33 testCases=((0,0,0),
34 (0,1,0),
35 (1,0,0),
36 (1,1,1))
37 for eachX1,eachX2,expected in testCases:
38
39 if isSame(eachX1,eachX2,w1,w2,expected):
40 continue
41 w1,w2=adjust(eachX1,eachX2,w1,w2,expected)
42 return w1,w2
43
44 def adjust(x1,x2,w1,w2,expected):
45 diffForW1=0.1*(expected-f(x1,x2,w1,w2))*x1
46 diffForW2=0.1*(expected-f(x1,x2,w1,w2))*x2
47 newW1=w1+diffForW1
48 newW2=w2+diffForW2
49 return newW1,newW2
50
51
52 def untilDone():
53 initialize()
54 iteration=0
55 while 1:
56 iteration+=1
57 calculateThisGeneration()
58 if everythingDone() or tooOld(iteration):
59 break
60 advanceGeneration()
61 printParameters()
62
63 def tooOld(iteration):
64 if iteration>=MAX_ITERATION:
65 raise "Too many iterations!"