Debian Codegraph @

rpython/translator/goal/bpnn.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """
3 Translator Demo
4
5 To analyse and type-annotate the functions and class defined in
6 this module, starting from the entry point function demo(),
7 use the following command line:
8
9 python2 rpython/bin/rpython rpython/translator/goal/bpnn.py
10
11 Insert '--help' before 'bpnn.py' for a list of translation options,
12 or see the Overview of Command Line Options for translation at
13 https://doc.pypy.org/config/index.html
14 """
15 # Back-Propagation Neural Networks
16 #
17 # Written in Python. See http://www.python.org/
18 #
19 # Neil Schemenauer <[email protected]>
20 #
21 # Modifications to the original (Armin Rigo):
22 # * import random from PyPy's lib, which is Python 2.2's plain
23 # Python implementation
24 # * print a doc about how to start the Translator
25
26 import sys
27 import math
28 import time
29
30 from rpython.rlib import rrandom
31
32 PRINT_IT = True
33
34 random = rrandom.Random(1)
35
36 # calculate a random number where: a <= rand < b
37 def rand(a, b):
38 return (b-a)*random.random() + a
39
40 # Make a matrix (we could use NumPy to speed this up)
41 def makeMatrix(I, J, fill=0.0):
42 m = []
43 for i in range(I):
44 m.append([fill]*J)
45 return m
46
47 class NN:
48
49 def __init__(self, ni, nh, no):
50 # number of input, hidden, and output nodes
51 self.ni = ni + 1 # +1 for bias node
52 self.nh = nh
53 self.no = no
54
55 # activations for nodes
56 self.ai = [1.0]*self.ni
57 self.ah = [1.0]*self.nh
58 self.ao = [1.0]*self.no
59
60 # create weights
61 self.wi = makeMatrix(self.ni, self.nh)
62 self.wo = makeMatrix(self.nh, self.no)
63 # set them to random values
64 for i in range(self.ni):
65 for j in range(self.nh):
66 self.wi[i][j] = rand(-2.0, 2.0)
67 for j in range(self.nh):
68 for k in range(self.no):
69 self.wo[j][k] = rand(-2.0, 2.0)
70
71 # last change in weights for momentum
72 self.ci = makeMatrix(self.ni, self.nh)
73 self.co = makeMatrix(self.nh, self.no)
74
75 def update(self, inputs):
76 if len(inputs) != self.ni-1:
77 raise ValueError('wrong number of inputs')
78
79 # input activations
80 for i in range(self.ni-1):
81 #self.ai[i] = 1.0/(1.0+math.exp(-inputs[i]))
82 self.ai[i] = inputs[i]
83
84 # hidden activations
85 for j in range(self.nh):
86 sum = 0.0
87 for i in range(self.ni):
88 sum = sum + self.ai[i] * self.wi[i][j]
89 self.ah[j] = 1.0/(1.0+math.exp(-sum))
90
91 # output activations
92 for k in range(self.no):
93 sum = 0.0
94 for j in range(self.nh):
95 sum = sum + self.ah[j] * self.wo[j][k]
96 self.ao[k] = 1.0/(1.0+math.exp(-sum))
97
98 return self.ao[:]
99
100
101 def backPropagate(self, targets, N, M):
102 if len(targets) != self.no:
103 raise ValueError('wrong number of target values')
104
105 # calculate error terms for output
106 output_deltas = [0.0] * self.no
107 for k in range(self.no):
108 ao = self.ao[k]
109 output_deltas[k] = ao*(1-ao)*(targets[k]-ao)
110
111 # calculate error terms for hidden
112 hidden_deltas = [0.0] * self.nh
113 for j in range(self.nh):
114 sum = 0.0
115 for k in range(self.no):
116 sum = sum + output_deltas[k]*self.wo[j][k]
117 hidden_deltas[j] = self.ah[j]*(1-self.ah[j])*sum
118
119 # update output weights
120 for j in range(self.nh):
121 for k in range(self.no):
122 change = output_deltas[k]*self.ah[j]
123 self.wo[j][k] = self.wo[j][k] + N*change + M*self.co[j][k]
124 self.co[j][k] = change
125 #print N*change, M*self.co[j][k]
126
127 # update input weights
128 for i in range(self.ni):
129 for j in range(self.nh):
130 change = hidden_deltas[j]*self.ai[i]
131 self.wi[i][j] = self.wi[i][j] + N*change + M*self.ci[i][j]
132 self.ci[i][j] = change
133
134 # calculate error
135 error = 0.0
136 for k in range(len(targets)):
137 delta = targets[k]-self.ao[k]
138 error = error + 0.5*delta*delta
139 return error
140
141
142 def test(self, patterns):
143 for p in patterns:
144 if PRINT_IT:
145 print p[0], '->', self.update(p[0])
146
147 def weights(self):
148 if PRINT_IT:
149 print 'Input weights:'
150 for i in range(self.ni):
151 print self.wi[i]
152 print
153 print 'Output weights:'
154 for j in range(self.nh):
155 print self.wo[j]
156
157 def train(self, patterns, iterations=2000, N=0.5, M=0.1):
158 # N: learning rate
159 # M: momentum factor
160 for i in xrange(iterations):
161 error = 0.0
162 for p in patterns:
163 inputs = p[0]
164 targets = p[1]
165 self.update(inputs)
166 error = error + self.backPropagate(targets, N, M)
167 if PRINT_IT and i % 100 == 0:
168 print 'error', error
169
170
171 def demo():
172 # Teach network XOR function
173 pat = [
174 [[0,0], [0]],
175 [[0,1], [1]],
176 [[1,0], [1]],
177 [[1,1], [0]]
178 ]
179
180 # create a network with two input, three hidden, and one output nodes
181 n = NN(2, 3, 1)
182 # train it with some patterns
183 n.train(pat, 2000)
184 # test it
185 n.test(pat)
186
187
188 # __________ Entry point for stand-alone builds __________
189
190 def entry_point(argv):
191 if len(argv) > 1:
192 N = int(argv[1])
193 else:
194 N = 200
195 T = time.time()
196 for i in range(N):
197 demo()
198 t1 = time.time() - T
199 print "%d iterations, %s milliseconds per iteration" % (N, 1000.0*t1/N)
200 return 0
201
202 # _____ Define and setup target ___
203
204 def target(*args):
205 return entry_point, None
206
207 if __name__ == '__main__':
208 if len(sys.argv) == 1:
209 sys.argv.append('1')
210 entry_point(sys.argv)
211 print __doc__