感知器基础原理及python实现过程详解

前端之家收集整理的这篇文章主要介绍了感知器基础原理及python实现过程详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

简单版本,按照李航的《统计学习方法》的思路编写

感知器基础原理及python实现过程详解

数据采用了著名的sklearn自带的iries数据,最优化求解采用了SGD算法。

预处理增加了标准化操作。

  1. '''
  2. perceptron classifier
  3.  
  4. created on 2019.9.14
  5. author: vince
  6. '''
  7. import pandas
  8. import numpy
  9. import logging
  10. import matplotlib.pyplot as plt
  11.  
  12. from sklearn.datasets import load_iris
  13. from sklearn.model_selection import train_test_split
  14. from sklearn.metrics import accuracy_score
  15.  
  16. '''
  17. perceptron classifier
  18.  
  19. Attributes
  20. w: ld-array = weights after training
  21. l: list = number of misclassification during each iteration
  22. '''
  23. class Perceptron:
  24. def __init__(self,eta = 0.01,iter_num = 50,batch_size = 1):
  25. '''
  26. eta: float = learning rate (between 0.0 and 1.0).
  27. iter_num: int = iteration over the training dataset.
  28. batch_size: int = gradient descent batch number,if batch_size == 1,used SGD;
  29. if batch_size == 0,use BGD;
  30. else MBGD;
  31. '''
  32.  
  33. self.eta = eta;
  34. self.iter_num = iter_num;
  35. self.batch_size = batch_size;
  36.  
  37. def train(self,X,Y):
  38. '''
  39. train training data.
  40. X:{array-like},shape=[n_samples,n_features] = Training vectors,where n_samples is the number of training samples and
  41. n_features is the number of features.
  42. Y:{array-like},share=[n_samples] = traget values.
  43. '''
  44. self.w = numpy.zeros(1 + X.shape[1]);
  45. self.l = numpy.zeros(self.iter_num);
  46. for iter_index in range(self.iter_num):
  47. for sample_index in range(X.shape[0]):
  48. if (self.activation(X[sample_index]) != Y[sample_index]):
  49. logging.debug("%s: pred(%s),label(%s),%s,%s" % (sample_index,self.net_input(X[sample_index]),Y[sample_index],X[sample_index,0],1]));
  50. self.l[iter_index] += 1;
  51. for sample_index in range(X.shape[0]):
  52. if (self.activation(X[sample_index]) != Y[sample_index]):
  53. self.w[0] += self.eta * Y[sample_index];
  54. self.w[1:] += self.eta * numpy.dot(X[sample_index],Y[sample_index]);
  55. break;
  56. logging.info("iter %s: %s,%s" %
  57. (iter_index,self.w[0],self.w[1],self.w[2],self.l[iter_index]));
  58.  
  59. def activation(self,x):
  60. return numpy.where(self.net_input(x) >= 0.0,1,-1);
  61.  
  62. def net_input(self,x):
  63. return numpy.dot(x,self.w[1:]) + self.w[0];
  64.  
  65. def predict(self,x):
  66. return self.activation(x);
  67.  
  68. def main():
  69. logging.basicConfig(level = logging.INFO,format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt = '%a,%d %b %Y %H:%M:%S');
  70.  
  71. iris = load_iris();
  72.  
  73. features = iris.data[:99,[0,2]];
  74. # normalization
  75. features_std = numpy.copy(features);
  76. for i in range(features.shape[1]):
  77. features_std[:,i] = (features_std[:,i] - features[:,i].mean()) / features[:,i].std();
  78.  
  79. labels = numpy.where(iris.target[:99] == 0,-1,1);
  80.  
  81. # 2/3 data from training,1/3 data for testing
  82. train_features,test_features,train_labels,test_labels = train_test_split(
  83. features_std,labels,test_size = 0.33,random_state = 23323);
  84.  
  85. logging.info("train set shape:%s" % (str(train_features.shape)));
  86.  
  87. p = Perceptron();
  88.  
  89. p.train(train_features,train_labels);
  90.  
  91. test_predict = numpy.array([]);
  92. for feature in test_features:
  93. predict_label = p.predict(feature);
  94. test_predict = numpy.append(test_predict,predict_label);
  95.  
  96. score = accuracy_score(test_labels,test_predict);
  97. logging.info("The accruacy score is: %s "% (str(score)));
  98.  
  99. #plot
  100. x_min,x_max = train_features[:,0].min() - 1,train_features[:,0].max() + 1;
  101. y_min,y_max = train_features[:,1].min() - 1,1].max() + 1;
  102. plt.xlim(x_min,x_max);
  103. plt.ylim(y_min,y_max);
  104. plt.xlabel("width");
  105. plt.ylabel("heigt");
  106.  
  107. plt.scatter(train_features[:,1],c = train_labels,marker = 'o',s = 10);
  108.  
  109. k = - p.w[1] / p.w[2];
  110. d = - p.w[0] / p.w[2];
  111.  
  112. plt.plot([x_min,x_max],[k * x_min + d,k * x_max + d],"go-");
  113.  
  114. plt.show();
  115.  
  116. if __name__ == "__main__":
  117. main();

感知器基础原理及python实现过程详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

猜你在找的Python相关文章