[关闭]
@cleardusk 2015-11-13T08:59:54.000000Z 字数 3369 阅读 1275

BP

GjzCVCode


  1. # Back-Propagation Neural Networks
  2. #
  3. # Written in Python. See http://www.python.org/
  4. # Placed in the public domain.
  5. # Neil Schemenauer <nas@arctrix.com>
  6. import math
  7. import random
  8. import string
  9. random.seed(0)
  10. # calculate a random number where: a <= rand < b
  11. def rand(a, b):
  12. return (b-a)*random.random() + a
  13. # Make a matrix (we could use NumPy to speed this up)
  14. def makeMatrix(I, J, fill=0.0):
  15. m = []
  16. for i in range(I):
  17. m.append([fill]*J)
  18. return m
  19. # our sigmoid function, tanh is a little nicer than the standard 1/(1+e^-x)
  20. def sigmoid(x):
  21. return math.tanh(x) # this is not sigmoid function, but it's effect is better
  22. # return 1.0/(math.exp(-x)+1.0) # this is really sigmoid function
  23. # derivative of our sigmoid function, in terms of the output (i.e. y)
  24. def dsigmoid(y):
  25. return 1.0 - y**2 # tanh
  26. # return y - y**2 # sigmoid
  27. class NN:
  28. def __init__(self, ni, nh, no):
  29. # number of input, hidden, and output nodes
  30. self.ni = ni + 1 # +1 for bias node
  31. self.nh = nh
  32. self.no = no
  33. # activations for nodes
  34. self.ai = [1.0]*self.ni
  35. self.ah = [1.0]*self.nh
  36. self.ao = [1.0]*self.no
  37. # create weights
  38. self.wi = makeMatrix(self.ni, self.nh)
  39. self.wo = makeMatrix(self.nh, self.no)
  40. # set them to random vaules
  41. for i in range(self.ni):
  42. for j in range(self.nh):
  43. self.wi[i][j] = rand(-0.2, 0.2)
  44. for j in range(self.nh):
  45. for k in range(self.no):
  46. self.wo[j][k] = rand(-2.0, 2.0)
  47. # last change in weights for momentum
  48. self.ci = makeMatrix(self.ni, self.nh)
  49. self.co = makeMatrix(self.nh, self.no)
  50. def update(self, inputs):
  51. if len(inputs) != self.ni-1:
  52. raise ValueError('wrong number of inputs')
  53. # input activations
  54. for i in range(self.ni-1):
  55. #self.ai[i] = sigmoid(inputs[i])
  56. self.ai[i] = inputs[i]
  57. # hidden activations
  58. for j in range(self.nh):
  59. sum = 0.0
  60. for i in range(self.ni):
  61. sum = sum + self.ai[i] * self.wi[i][j]
  62. self.ah[j] = sigmoid(sum)
  63. # output activations
  64. for k in range(self.no):
  65. sum = 0.0
  66. for j in range(self.nh):
  67. sum = sum + self.ah[j] * self.wo[j][k]
  68. self.ao[k] = sigmoid(sum)
  69. return self.ao[:]
  70. def backPropagate(self, targets, N, M):
  71. if len(targets) != self.no:
  72. raise ValueError('wrong number of target values')
  73. # calculate error terms for output
  74. output_deltas = [0.0] * self.no
  75. for k in range(self.no):
  76. error = targets[k]-self.ao[k]
  77. output_deltas[k] = dsigmoid(self.ao[k]) * error
  78. # calculate error terms for hidden
  79. hidden_deltas = [0.0] * self.nh
  80. for j in range(self.nh):
  81. error = 0.0
  82. for k in range(self.no):
  83. error = error + output_deltas[k]*self.wo[j][k]
  84. hidden_deltas[j] = dsigmoid(self.ah[j]) * error
  85. # update output weights
  86. for j in range(self.nh):
  87. for k in range(self.no):
  88. change = output_deltas[k]*self.ah[j]
  89. # self.wo[j][k] = self.wo[j][k] + N*change + M*self.co[j][k]
  90. self.wo[j][k] = self.wo[j][k] + N*change
  91. self.co[j][k] = change
  92. #print N*change, M*self.co[j][k]
  93. # update input weights
  94. for i in range(self.ni):
  95. for j in range(self.nh):
  96. change = hidden_deltas[j]*self.ai[i]
  97. # self.wi[i][j] = self.wi[i][j] + N*change + M*self.ci[i][j]
  98. self.wi[i][j] = self.wi[i][j] + N*change
  99. self.ci[i][j] = change
  100. # calculate error
  101. error = 0.0
  102. for k in range(len(targets)):
  103. error = error + 0.5*(targets[k]-self.ao[k])**2
  104. return error
  105. def test(self, patterns):
  106. for p in patterns:
  107. print(p[0], '->', self.update(p[0]))
  108. def weights(self):
  109. print('Input weights:')
  110. for i in range(self.ni):
  111. print(self.wi[i])
  112. print()
  113. print('Output weights:')
  114. for j in range(self.nh):
  115. print(self.wo[j])
  116. def train(self, patterns, iterations=1000, N=0.5, M=0.1):
  117. # N: learning rate
  118. # M: momentum factor
  119. for i in range(iterations):
  120. error = 0.0
  121. for p in patterns:
  122. inputs = p[0]
  123. targets = p[1]
  124. self.update(inputs)
  125. error = error + self.backPropagate(targets, N, M)
  126. if i % 100 == 0:
  127. print('error %-.5f' % error)
  128. def demo():
  129. # Teach network XOR function
  130. pat = [
  131. [[0,0], [0]],
  132. [[0,1], [1]],
  133. [[1,0], [1]],
  134. [[1,1], [0]]
  135. ]
  136. # create a network with two input, two hidden, and one output nodes
  137. n = NN(2, 2, 1)
  138. # train it with some patterns
  139. n.train(pat)
  140. # test it
  141. n.test(pat)
  142. if __name__ == '__main__':
  143. demo()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注