一、基本结构

神经网络基本结构 ANN神经网络 - 图1 ANN神经网络 - 图2

何为深度学习? ANN神经网络 - 图3

二、感知器和激活函数

感知器 ANN神经网络 - 图4

激活函数(其中w和x为向量点乘;b为偏置,w0) ANN神经网络 - 图5

激活函数的选择 ANN神经网络 - 图6

三、感知器的训练

ANN神经网络 - 图7

四、简单代码实现

  1. from functools import reduce
  2. class Perceptron(object):
  3. '''
  4. 构造函数的初始化
  5. '''
  6. def __init__(self,input_num,activator):
  7. '''
  8. 构造函数的初始化
  9. '''
  10. self.activator = activator
  11. self.weights = [0.0 for _ in range(input_num)]
  12. self.bias = 0.0
  13. def __str__(self):
  14. '''
  15. 打印学习后的权重值和偏置项
  16. '''
  17. return 'weights\t:%s\nbias\t:%f\n' %(self.weights,self.bias)
  18. def predict(self,input_vec):
  19. '''
  20. 输入向量,输出感知器的计算结果
  21. '''
  22. return self.activator(
  23. reduce(lambda a,b: a+b,
  24. list(map(lambda x,w: x*w,
  25. input_vec,self.weights)
  26. ),0.0)+self.bias)
  27. def train(self,input_vecs,labels,iteration,rate):
  28. '''
  29. 输入训练数据:一组向量、与每个向量对应的label;以及训练轮数、学习率
  30. '''
  31. for i in range(iteration):
  32. self._one_iteration(input_vecs,labels,rate)
  33. def _one_iteration(self,input_vecs,labels,rate):
  34. '''
  35. 迭代,把所有的训练数据过一遍
  36. '''
  37. samples = zip(input_vecs,labels)
  38. for (input_vec,label) in samples:
  39. output = self.predict(input_vec)
  40. self._update_weights(input_vec,output,label,rate)
  41. def _update_weights(self,input_vec,output,label,rate):
  42. '''
  43. 按照感知器规则更新权重
  44. '''
  45. delta = label - output
  46. self.weights = map(
  47. lambda x, w:w+rate*delta*x,
  48. input_vec,self.weights)
  49. self.weights = list(self.weights)
  50. self.bias += rate*delta
  51. def f(x):
  52. '''
  53. 定义激活函数
  54. '''
  55. return 1 if x>0 else 0
  56. def get_training_dataset():
  57. '''
  58. 训练数据
  59. '''
  60. input_vecs = [[1,1],[0,0],[1,0],[0,1]]
  61. labels = [1,0,0,0]
  62. return input_vecs,labels
  63. def train_and_perceptron():
  64. '''
  65. 训练感知器
  66. '''
  67. p = Perceptron(2,f)
  68. input_vecs,labels = get_training_dataset()
  69. p.train(input_vecs,labels,10,0.1)
  70. return p
  71. if __name__ == '__main__':
  72. and_perception = train_and_perceptron()
  73. print(and_perception)
  74. print('1 and 1 = %d' % and_perception.predict([1,1]))
  75. print('0 and 0 = %d' % and_perception.predict([0,0]))
  76. print('1 and 0 = %d' % and_perception.predict([1,0]))
  77. print('0 and 1 = %d' % and_perception.predict([0,1]))

运行结果: ANN神经网络 - 图8