感知器基础原理及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设计模式大全
Jun 27 Python
Python实现按特定格式对文件进行读写的方法示例
Nov 30 Python
windows下安装python的C扩展编译环境(解决Unable to find vcvarsall.bat)
Feb 21 Python
Python输入二维数组方法
Apr 13 Python
详解python如何在django中为用户模型添加自定义权限
Oct 15 Python
基于python指定包的安装路径方法
Oct 27 Python
Python字符串逆序输出的实例讲解
Feb 16 Python
python提取log文件内容并画出图表
Jul 08 Python
python实现字典嵌套列表取值
Dec 16 Python
解决Python3.8用pip安装turtle-0.0.2出现错误问题
Feb 11 Python
python元组打包和解包过程详解
Aug 02 Python
Python内置类型集合set和frozenset的使用详解
Apr 26 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创建session的方法实例详解
2015/01/27 PHP
PHP 数组黑名单/白名单实例代码详解
2019/06/04 PHP
jquery 实现的全选和反选
2009/04/15 Javascript
十个迅速提升JQuery性能让你的JQuery跑得更快
2012/12/10 Javascript
checkbox设置复选框的只读效果不让用户勾选
2013/08/12 Javascript
javascript scrollTop正解使用方法
2013/11/14 Javascript
JavaScript Ajax Json实现上下级下拉框联动效果实例代码
2013/11/23 Javascript
Extjs4中tree的拖拽功能(可以两棵树之间拖拽) 简单实例
2013/12/08 Javascript
jquery控制页面部分刷新的方法
2015/06/24 Javascript
jQuery+CSS3折叠卡片式下拉列表框实现效果
2015/11/02 Javascript
辨析JavaScript中的Undefined类型与null类型
2016/05/26 Javascript
使用Promise链式调用解决多个异步回调的问题
2017/01/15 Javascript
详解webpack异步加载业务模块
2017/06/23 Javascript
Vue2.0如何发布项目实战
2017/07/27 Javascript
Js中async/await的执行顺序详解
2017/09/22 Javascript
webpack 静态资源集中输出的方法示例
2018/11/09 Javascript
详解vue 路由跳转四种方式 (带参数)
2019/04/28 Javascript
javascript设计模式 ? 模板方法模式原理与用法实例分析
2020/04/23 Javascript
Vue 3.0 全家桶抢先体验
2020/04/28 Javascript
零基础写python爬虫之使用urllib2组件抓取网页内容
2014/11/04 Python
使用python实现tcp自动重连
2017/07/02 Python
Numpy数组转置的两种实现方法
2018/04/17 Python
python 对类的成员函数开启线程的方法
2019/01/22 Python
Python离线安装各种库及pip的方法
2020/11/28 Python
小程序canvas中文字设置居中锚点
2019/04/16 HTML / CSS
《灯光》教学反思
2014/02/08 职场文书
公司演讲稿开场白
2014/08/25 职场文书
大学拉赞助协议书范文
2014/09/26 职场文书
2015年九一八事变纪念活动实施方案
2015/05/06 职场文书
地雷战观后感
2015/06/09 职场文书
入党宣誓仪式主持词
2015/06/29 职场文书
2019单位介绍信怎么写
2019/06/24 职场文书
ThinkPHP5和ThinkPHP6的区别
2021/03/31 PHP
python基础之模块的导入
2021/10/24 Python
JavaScript高级程序设计之变量与作用域
2021/11/17 Javascript
Redis中有序集合的内部实现方式的详细介绍
2022/03/16 Redis