感知器基础原理及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 创建弹出式菜单的实现代码
Jul 11 Python
Python2.7环境Flask框架安装简明教程【已测试】
Jul 13 Python
判断python对象是否可调用的三种方式及其区别详解
Jan 31 Python
python opencv将表格图片按照表格框线分割和识别
Oct 30 Python
Python sys模块常用方法解析
Feb 20 Python
使用Python将图片转正方形的两种方法实例代码详解
Apr 29 Python
python输入一个水仙花数(三位数) 输出百位十位个位实例
May 03 Python
django 实现后台从富文本提取纯文本
Jul 02 Python
详解python方法之绑定方法与非绑定方法
Aug 17 Python
Python selenium实现断言3种方法解析
Sep 08 Python
Python实战之用tkinter库做一个鼠标模拟点击器
Apr 27 Python
Python+Selenium实现抖音、快手、B站、小红书、微视、百度好看视频、西瓜视频、微信视频号、搜狐视频、一点号、大风号、趣头条等短视频自动发布
Apr 13 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
smarty自定义函数htmlcheckboxes用法实例
2015/01/22 PHP
PHP递归实现层级树状展开
2016/04/01 PHP
jquery pagination插件实现无刷新分页代码
2009/10/13 Javascript
基于jquery实现后台左侧菜单点击上下滑动显示
2013/04/11 Javascript
jquery中EasyUI实现异步树
2015/03/01 Javascript
详解javascript实现瀑布流列式布局
2016/01/29 Javascript
微信小程序开发之改变data中数组或对象的某一属性值
2018/07/05 Javascript
浅谈Vue.use的使用
2018/08/29 Javascript
Vue+Webpack完美整合富文本编辑器TinyMce的方法
2018/11/30 Javascript
Vue.set 全局操作简单示例
2019/09/19 Javascript
javascript随机变色实例代码
2019/10/15 Javascript
[32:36]完美世界DOTA2联赛PWL S3 LBZS vs CPG 第二场 12.12
2020/12/16 DOTA
Python实现Linux的find命令实例分享
2017/06/04 Python
python实现读取excel写入mysql的小工具详解
2017/11/20 Python
浅谈python 里面的单下划线与双下划线的区别
2017/12/01 Python
django实现用户登陆功能详解
2017/12/11 Python
python+selenium识别验证码并登录的示例代码
2017/12/21 Python
Ubuntu16.04/树莓派Python3+opencv配置教程(分享)
2018/04/02 Python
windows下添加Python环境变量的方法汇总
2018/05/14 Python
如何用C代码给Python写扩展库(Cython)
2019/05/17 Python
python代码编写计算器小程序
2020/03/30 Python
pytorch::Dataloader中的迭代器和生成器应用详解
2020/01/03 Python
Python Websocket服务端通信的使用示例
2020/02/25 Python
深入浅析Python 命令行模块 Click
2020/03/11 Python
Python如何使用PIL Image制作GIF图片
2020/05/16 Python
Python多个装饰器的调用顺序实例解析
2020/05/22 Python
Python将字典转换为XML的方法
2020/08/01 Python
python 如何用urllib与服务端交互(发送和接收数据)
2021/03/04 Python
CSS3 :not()选择器实现最后一行li去除某种css样式
2016/10/19 HTML / CSS
争论的故事教学反思
2014/02/06 职场文书
学校个人对照检查材料
2014/08/26 职场文书
公民授权委托书范本
2014/09/17 职场文书
个人自查自纠材料
2014/10/14 职场文书
星际争霸:毕姥爷vs解冻01
2022/04/01 星际争霸
python如何将mat文件转为png
2022/07/15 Python
HTML中link标签属性的具体用法
2023/05/07 HTML / CSS