感知器基础原理及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中endswith()函数的基本使用
Apr 07 Python
python执行get提交的方法
Apr 29 Python
Python的条件语句与运算符优先级详解
Oct 13 Python
使用sklearn进行对数据标准化、归一化以及将数据还原的方法
Jul 11 Python
Python tkinter label 更新方法
Oct 11 Python
Python异常模块traceback用法实例分析
Oct 22 Python
使用python3 实现插入数据到mysql
Mar 02 Python
Pycharm pyuic5实现将ui文件转为py文件,让UI界面成功显示
Apr 08 Python
python 画图 图例自由定义方式
Apr 17 Python
keras训练浅层卷积网络并保存和加载模型实例
Jul 02 Python
Python析构函数__del__定义原理解析
Nov 20 Python
Python Django框架介绍之模板标签及模板的继承
May 27 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 变量的定义方法
2010/01/26 PHP
PHP flush()与ob_flush()的区别详解
2013/06/03 PHP
PHP rawurlencode与urlencode函数的深入分析
2013/06/08 PHP
深入Apache与Nginx的优缺点比较详解
2013/06/17 PHP
PHP捕获Fatal error错误的方法
2014/06/11 PHP
PHP命名空间(Namespace)简明教程
2014/06/11 PHP
php使用scandir()函数扫描指定目录下所有文件示例
2019/06/08 PHP
php中try catch捕获异常实例详解
2020/08/06 PHP
top.location.href 没有权限 解决方法
2008/08/05 Javascript
javascript 原型模式实现OOP的再研究
2009/04/09 Javascript
有效提高JavaScript执行效率的几点知识
2015/01/31 Javascript
JS基于VML技术实现的五角星礼花效果代码
2015/10/26 Javascript
基于jQuery实现动态搜索显示功能
2016/05/05 Javascript
实例解析js中try、catch、finally的执行规则
2017/02/24 Javascript
浅谈React 服务器端渲染的使用
2018/05/08 Javascript
jquery 验证用户名是否重复代码实例
2019/05/14 jQuery
vue实现自定义H5视频播放器的方法步骤
2019/07/01 Javascript
浅谈VUE中演示v-for为什么要加key
2020/01/16 Javascript
python 获取本机ip地址的两个方法
2013/02/25 Python
Python获取远程文件大小的函数代码分享
2014/05/13 Python
Python按行读取文件的简单实现方法
2016/06/22 Python
Python装饰器的执行过程实例分析
2018/06/04 Python
PyCharm的设置方法和第一个Python程序的建立
2019/01/16 Python
Python实现FTP文件传输的实例
2019/07/07 Python
django中上传图片分页三级联动效果的实现代码
2019/08/30 Python
用python对excel进行操作(读,写,修改)
2020/12/25 Python
用Python实现职工信息管理系统
2020/12/30 Python
校园报刊亭创业计划书
2014/01/02 职场文书
成龙霸王洗发水广告词
2014/03/14 职场文书
大学生党员学习焦裕禄精神思想汇报
2014/09/10 职场文书
退税申请报告怎么写
2015/05/18 职场文书
银行服务理念口号
2015/12/25 职场文书
曾国藩励志经典名言37句,蕴含哲理
2019/10/14 职场文书
python自动化之如何利用allure生成测试报告
2021/05/02 Python
Vue3.0写自定义指令的简单步骤记录
2021/06/27 Vue.js
Python中re模块的元字符使用小结
2022/04/07 Python