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


Posted in Python onSeptember 30, 2019

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

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

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

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

'''
perceptron classifier

created on 2019.9.14
author: vince
'''
import pandas 
import numpy 
import logging
import matplotlib.pyplot as plt

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

'''
perceptron classifier

Attributes
w: ld-array = weights after training
l: list = number of misclassification during each iteration 
'''
class Perceptron:
  def __init__(self, eta = 0.01, iter_num = 50, batch_size = 1):
    '''
    eta: float = learning rate (between 0.0 and 1.0).
    iter_num: int = iteration over the training dataset.
    batch_size: int = gradient descent batch number, 
      if batch_size == 1, used SGD; 
      if batch_size == 0, use BGD; 
      else MBGD;
    '''

    self.eta = eta;
    self.iter_num = iter_num;
    self.batch_size = batch_size;

  def train(self, X, Y):
    '''
    train training data.
    X:{array-like}, shape=[n_samples, n_features] = Training vectors, 
      where n_samples is the number of training samples and 
      n_features is the number of features.
    Y:{array-like}, share=[n_samples] = traget values.
    '''
    self.w = numpy.zeros(1 + X.shape[1]);
    self.l = numpy.zeros(self.iter_num);
    for iter_index in range(self.iter_num):
      for sample_index in range(X.shape[0]): 
        if (self.activation(X[sample_index]) != Y[sample_index]):
          logging.debug("%s: pred(%s), label(%s), %s, %s" % (sample_index, 
            self.net_input(X[sample_index]) , Y[sample_index],
            X[sample_index, 0], X[sample_index, 1]));
          self.l[iter_index] += 1;
      for sample_index in range(X.shape[0]): 
        if (self.activation(X[sample_index]) != Y[sample_index]):
          self.w[0] += self.eta * Y[sample_index];
          self.w[1:] += self.eta * numpy.dot(X[sample_index], Y[sample_index]);
          break;
      logging.info("iter %s: %s, %s, %s, %s" %
          (iter_index, self.w[0], self.w[1], self.w[2], self.l[iter_index]));

  def activation(self, x):
    return numpy.where(self.net_input(x) >= 0.0 , 1 , -1);

  def net_input(self, x): 
    return numpy.dot(x, self.w[1:]) + self.w[0];

  def predict(self, x):
    return self.activation(x);

def main():
  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');

  iris = load_iris();

  features = iris.data[:99, [0, 2]];
  # normalization
  features_std = numpy.copy(features);
  for i in range(features.shape[1]):
    features_std[:, i] = (features_std[:, i] - features[:, i].mean()) / features[:, i].std();

  labels = numpy.where(iris.target[:99] == 0, -1, 1);

  # 2/3 data from training, 1/3 data for testing
  train_features, test_features, train_labels, test_labels = train_test_split(
      features_std, labels, test_size = 0.33, random_state = 23323);
  
  logging.info("train set shape:%s" % (str(train_features.shape)));

  p = Perceptron();

  p.train(train_features, train_labels);
    
  test_predict = numpy.array([]);
  for feature in test_features:
    predict_label = p.predict(feature);
    test_predict = numpy.append(test_predict, predict_label);

  score = accuracy_score(test_labels, test_predict);
  logging.info("The accruacy score is: %s "% (str(score)));

  #plot
  x_min, x_max = train_features[:, 0].min() - 1, train_features[:, 0].max() + 1;
  y_min, y_max = train_features[:, 1].min() - 1, train_features[:, 1].max() + 1;
  plt.xlim(x_min, x_max);
  plt.ylim(y_min, y_max);
  plt.xlabel("width");
  plt.ylabel("heigt");

  plt.scatter(train_features[:, 0], train_features[:, 1], c = train_labels, marker = 'o', s = 10);

  k = - p.w[1] / p.w[2];
  d = - p.w[0] / p.w[2];

  plt.plot([x_min, x_max], [k * x_min + d, k * x_max + d], "go-");

  plt.show();
  

if __name__ == "__main__":
  main();

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

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

Python 相关文章推荐
python批量导出导入MySQL用户的方法
Nov 15 Python
Python中的列表生成式与生成器学习教程
Mar 13 Python
详解python中字典的循环遍历的两种方式
Feb 07 Python
浅谈Python中的作用域规则和闭包
Mar 20 Python
如何在django里上传csv文件并进行入库处理的方法
Jan 02 Python
Python实现简单石头剪刀布游戏
Jan 20 Python
通过python爬虫赚钱的方法
Jan 29 Python
python定时检测无响应进程并重启的实例代码
Apr 22 Python
python图形开发GUI库pyqt5的基本使用方法详解
Feb 14 Python
Python序列化pickle模块使用详解
Mar 05 Python
Django中的session用法详解
Mar 09 Python
Python实现Wordcloud生成词云图的示例
Mar 30 Python
基于python的BP神经网络及异或实现过程解析
Sep 30 #Python
Window10下python3.7 安装与卸载教程图解
Sep 30 #Python
Python检查图片是否损坏及图片类型是否正确过程详解
Sep 30 #Python
Python3 合并二叉树的实现
Sep 30 #Python
自适应线性神经网络Adaline的python实现详解
Sep 30 #Python
softmax及python实现过程解析
Sep 30 #Python
python根据时间获取周数代码实例
Sep 30 #Python
You might like
PHP小程序自动提交到自助友情连接
2009/11/24 PHP
php Xdebug 调试扩展的安装与使用.
2010/03/13 PHP
PHP中::、->、self、$this几种操作符的区别介绍
2013/04/24 PHP
laravel 字段格式化 modle 字段类型转换方法
2019/09/30 PHP
laravel config文件配置全局变量的例子
2019/10/13 PHP
Mootools 图片展示插件(lightbox,ImageMenu)收集集合
2010/05/21 Javascript
js获取指定日期周数以及星期几的小例子
2014/06/27 Javascript
深入分析JSON编码格式提交表单数据
2015/06/25 Javascript
Vue.js tab实现选项卡切换
2017/05/16 Javascript
nodejs批量下载图片的实现方法
2017/05/19 NodeJs
Angular 4依赖注入学习教程之InjectToken的使用(八)
2017/06/04 Javascript
Angular简单验证功能示例
2017/12/22 Javascript
微信小程序实现的点击按钮 弹出底部上拉菜单功能示例
2018/12/20 Javascript
JavaScript错误处理操作实例详解
2019/01/04 Javascript
bootstrapValidator表单校验、更改状态、新增、移除校验字段的实例代码
2020/05/19 Javascript
MySQL最常见的操作语句小结
2015/05/07 Python
python脚本监控docker容器
2016/04/27 Python
Python多维/嵌套字典数据无限遍历的实现
2016/11/04 Python
Python遍历文件夹和读写文件的实现方法
2017/05/10 Python
python如何派生内置不可变类型并修改实例化行为
2018/03/21 Python
在windows下Python打印彩色字体的方法
2018/05/15 Python
基于MTCNN/TensorFlow实现人脸检测
2018/05/24 Python
Python类装饰器实现方法详解
2018/12/21 Python
pytorch 获取层权重,对特定层注入hook, 提取中间层输出的方法
2019/08/17 Python
python 使用while写猜年龄小游戏过程解析
2019/10/07 Python
利用PyQt中的QThread类实现多线程
2020/02/18 Python
基于python和flask实现http接口过程解析
2020/06/15 Python
解决keras GAN训练是loss不发生变化,accuracy一直为0.5的问题
2020/07/02 Python
文秘专业应届生求职信
2014/05/26 职场文书
公共艺术专业自荐信
2014/09/01 职场文书
专题组织生活会思想汇报
2014/10/01 职场文书
2014流动人口计划生育工作总结
2014/12/20 职场文书
合同审查法律意见书
2015/06/04 职场文书
党员反腐倡廉学习心得体会
2015/08/15 职场文书
Vue详细的入门笔记
2021/05/10 Vue.js
HTML怎么设置下划线?html文字加下划线方法
2021/12/06 HTML / CSS