Guest User

Untitled

a guest
Feb 14th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. class Perceptron(object):
  4. def __init__(self, input_num, activator):
  5. '''
  6. 初始化感知器,设置输入参数的个数,以及激活函数。
  7. 激活函数的类型为double -> double
  8. '''
  9. self.activator = activator
  10. # 权重向量初始化为0
  11. self.weights = [0.0 for _ in range(input_num)]
  12. # 偏置项初始化为0
  13. self.bias = 0.0
  14. def __str__(self):
  15. '''
  16. 打印学习到的权重、偏置项
  17. '''
  18. return 'weights\t:%s\nbias\t:%f\n' % (self.weights, self.bias)
  19. def predict(self, input_vec):
  20. '''
  21. 输入向量,输出感知器的计算结果
  22. '''
  23. # 把input_vec[x1,x2,x3...]和weights[w1,w2,w3,...]打包在一起
  24. # 变成[(x1,w1),(x2,w2),(x3,w3),...]
  25. # 然后利用map函数计算[x1*w1, x2*w2, x3*w3]
  26. # 最后利用reduce求和
  27. return self.activator(
  28. reduce(lambda a, b: a + b,
  29. map(lambda (x, w): x * w,
  30. zip(input_vec, self.weights))
  31. , 0.0) + self.bias)
  32. def train(self, input_vecs, labels, iteration, rate):
  33. '''
  34. 输入训练数据:一组向量、与每个向量对应的label;以及训练轮数、学习率
  35. '''
  36. for i in range(iteration):
  37. self._one_iteration(input_vecs, labels, rate)
  38. def _one_iteration(self, input_vecs, labels, rate):
  39. '''
  40. 一次迭代,把所有的训练数据过一遍
  41. '''
  42. # 把输入和输出打包在一起,成为样本的列表[(input_vec, label), ...]
  43. # 而每个训练样本是(input_vec, label)
  44. samples = zip(input_vecs, labels)
  45. # 对每个样本,按照感知器规则更新权重
  46. for (input_vec, label) in samples:
  47. # 计算感知器在当前权重下的输出
  48. output = self.predict(input_vec)
  49. # 更新权重
  50. self._update_weights(input_vec, output, label, rate)
  51. def _update_weights(self, input_vec, output, label, rate):
  52. '''
  53. 按照感知器规则更新权重
  54. '''
  55. # 把input_vec[x1,x2,x3,...]和weights[w1,w2,w3,...]打包在一起
  56. # 变成[(x1,w1),(x2,w2),(x3,w3),...]
  57. # 然后利用感知器规则更新权重
  58. delta = label - output
  59. self.weights = map(
  60. lambda (x, w): w + rate * delta * x,
  61. zip(input_vec, self.weights))
  62. # 更新bias
  63. self.bias += rate * delta
Add Comment
Please, Sign In to add comment