Advertisement
here2share

# backprop.py

Nov 8th, 2019
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.06 KB | None | 0 0
  1. # backprop.py
  2. # Back-Propagation Neural Networks
  3. #
  4. # Written in Python.  See http://www.python.org/
  5. # Placed in the public domain.
  6. # Neil Schemenauer <nas@arctrix.com>
  7.  
  8. import math
  9. import random
  10. import string
  11.  
  12. # random.seed(0)
  13.  
  14. # calculate a random number where:  a <= rand < b
  15. def rand(a, b):
  16.     return (b-a)*random.random() + a
  17.  
  18. # Make a matrix (we could use NumPy to speed this up)
  19. def makeMatrix(I, J, fill=0.0):
  20.     m = []
  21.     for i in range(I):
  22.         m.append([fill]*J)
  23.     return m
  24.  
  25. # our sigmoid function, tanh is a little nicer than the standard 1/(1+e^-x)
  26. def sigmoid(x):
  27.     return math.tanh(x)
  28.  
  29. # derivative of our sigmoid function, in terms of the output (i.e. y)
  30. def dsigmoid(y):
  31.     return 1.0 - y**2
  32.  
  33. class NN:
  34.     def __init__(self, ni, nh, no):
  35.         # number of input, hidden, and output nodes
  36.         self.ni = ni + 1 # +1 for bias node
  37.         self.nh = nh
  38.         self.no = no
  39.  
  40.         # activations for nodes
  41.         self.ai = [1.0]*self.ni
  42.         self.ah = [1.0]*self.nh
  43.         self.ao = [1.0]*self.no
  44.  
  45.         # create weights
  46.         self.wi = makeMatrix(self.ni, self.nh)
  47.         self.wo = makeMatrix(self.nh, self.no)
  48.         # set them to random vaules
  49.         for i in range(self.ni):
  50.             for j in range(self.nh):
  51.                 self.wi[i][j] = rand(-0.2, 0.2)
  52.         for j in range(self.nh):
  53.             for k in range(self.no):
  54.                 self.wo[j][k] = rand(-2.0, 2.0)
  55.  
  56.         # last change in weights for momentum  
  57.         self.ci = makeMatrix(self.ni, self.nh)
  58.         self.co = makeMatrix(self.nh, self.no)
  59.  
  60.     def update(self, inputs):
  61.         if len(inputs) != self.ni-1:
  62.             raise ValueError, 'wrong number of inputs'
  63.  
  64.         # input activations
  65.         for i in range(self.ni-1):
  66.             #self.ai[i] = sigmoid(inputs[i])
  67.             self.ai[i] = inputs[i]
  68.  
  69.         # hidden activations
  70.         for j in range(self.nh):
  71.             summ = 0.0
  72.             for i in range(self.ni):
  73.                 summ = summ + self.ai[i] * self.wi[i][j]
  74.             self.ah[j] = sigmoid(summ)
  75.  
  76.         # output activations
  77.         for k in range(self.no):
  78.             summ = 0.0
  79.             for j in range(self.nh):
  80.                 summ = summ + self.ah[j] * self.wo[j][k]
  81.             self.ao[k] = sigmoid(summ)
  82.  
  83.         return self.ao[:]
  84.  
  85.  
  86.     def backPropagate(self, targets, N, M):
  87.         if len(targets) != self.no:
  88.             raise ValueError, 'wrong number of target values'
  89.  
  90.         # calculate error terms for output
  91.         output_deltas = [0.0] * self.no
  92.         for k in range(self.no):
  93.             error = targets[k]-self.ao[k]
  94.             output_deltas[k] = dsigmoid(self.ao[k]) * error
  95.  
  96.         # calculate error terms for hidden
  97.         hidden_deltas = [0.0] * self.nh
  98.         for j in range(self.nh):
  99.             error = 0.0
  100.             for k in range(self.no):
  101.                 error = error + output_deltas[k]*self.wo[j][k]
  102.             hidden_deltas[j] = dsigmoid(self.ah[j]) * error
  103.  
  104.         # update output weights
  105.         for j in range(self.nh):
  106.             for k in range(self.no):
  107.                 change = output_deltas[k]*self.ah[j]
  108.                 self.wo[j][k] = self.wo[j][k] + N*change + M*self.co[j][k]
  109.                 self.co[j][k] = change
  110.                 #print N*change, M*self.co[j][k]
  111.  
  112.         # update input weights
  113.         for i in range(self.ni):
  114.             for j in range(self.nh):
  115.                 change = hidden_deltas[j]*self.ai[i]
  116.                 self.wi[i][j] = self.wi[i][j] + N*change + M*self.ci[i][j]
  117.                 self.ci[i][j] = change
  118.  
  119.         # calculate error
  120.         error = 0.0
  121.         for k in range(len(targets)):
  122.             error = error + 0.5*(targets[k]-self.ao[k])**2
  123.         return error
  124.  
  125.  
  126.     def test(self, patterns):
  127.         for p in patterns:
  128.             print p[0], '->', self.update(p[0])
  129.  
  130.     def weights(self):
  131.         print 'Input weights:'
  132.         for i in range(self.ni):
  133.             print self.wi[i]
  134.         print
  135.         print 'Output weights:'
  136.         for j in range(self.nh):
  137.             print self.wo[j]
  138.  
  139.     def train(self, patterns, iterations=1000, N=0.5, M=0.1):
  140.         # N: learning rate
  141.         # M: momentum factor
  142.         for i in xrange(iterations):
  143.             error = 0.0
  144.             for p in patterns:
  145.                 inputs = p[0]
  146.                 targets = p[1]
  147.                 self.update(inputs)
  148.                 error = error + self.backPropagate(targets, N, M)
  149.             if i % 100 == 0:
  150.                 pass #print 'error %-14f' % error
  151.  
  152.  
  153. def demo():
  154.     # Teach network XOR function
  155.     pat = [
  156.         [[0,0,0], [0]],
  157.         [[0,0,1], [0]],
  158.         [[0,1,1], [0]],
  159.         [[1,1,0], [0]],
  160.         [[1,1,1], [0]],
  161.         [[0,1,0], [1]],
  162.         [[1,0,1], [1]],
  163.         [[1,0,0], [1]]
  164.     ]
  165.  
  166.     # create a network with two input, two hidden, and one output nodes
  167.     n = NN(3, 2, 1)
  168.     # train it with some patterns
  169.     n.train(pat)
  170.     # test it
  171.     n.test(pat)
  172.  
  173.  
  174.  
  175. if __name__ == '__main__':
  176.     demo()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement