感知器基础原理及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中apply函数的用法实例教程
Jul 31 Python
python类继承用法实例分析
May 27 Python
详解Django中的form库的使用
Jul 18 Python
详解python3中tkinter知识点
Jun 21 Python
pyqt5使用按钮进行界面的跳转方法
Jun 19 Python
django 信号调度机制详解
Jul 19 Python
Python 私有化操作实例分析
Nov 21 Python
Python的对象传递与Copy函数使用详解
Dec 26 Python
Pytorch框架实现mnist手写库识别(与tensorflow对比)
Jul 20 Python
Python 多线程C段扫描、检测 Ping扫描脚本的实现
Sep 03 Python
python爬取2021猫眼票房字体加密实例
Feb 19 Python
python代码实现扫码关注公众号登录的实战
Nov 01 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+java实现自动新闻滚动窗口
2006/10/09 PHP
Smarty安装配置方法
2008/04/10 PHP
php 字符串中的\n换行符无效、不能换行的解决方法
2014/04/02 PHP
PHP写的资源下载防盗链类分享
2014/05/12 PHP
详解PHP队列的实现
2019/03/14 PHP
PHP实现爬虫爬取图片代码实例
2021/03/03 PHP
用javascript动态调整iframe高度的方法
2007/03/06 Javascript
jQuery 点击图片跳转上一张或下一张功能的实现代码
2010/03/12 Javascript
纯Javascript实现Windows 8 Metro风格实现
2013/10/15 Javascript
ExtJS自定义主题(theme)样式详解
2013/11/18 Javascript
JQuery中阻止事件冒泡几种方式及其区别介绍
2014/01/15 Javascript
jquery选择器使用详解
2014/04/08 Javascript
jquery实现鼠标滑过显示提示框的方法
2015/02/05 Javascript
基于jquery实现鼠标左右拖动滑块滑动附源码下载
2015/12/23 Javascript
微信小程序左滑动显示菜单功能的实现
2018/06/14 Javascript
JavaScript函数节流和函数去抖知识点学习
2018/07/31 Javascript
vue-cli脚手架搭建的项目去除eslint验证的方法
2018/09/29 Javascript
js的各种数据类型判断的介绍
2019/01/19 Javascript
vue2.0实现的tab标签切换效果(内容可自定义)示例
2019/02/11 Javascript
js中apply和call的理解与使用方法
2019/11/27 Javascript
Python实现多行注释的另类方法
2014/08/22 Python
Python利用operator模块实现对象的多级排序详解
2017/05/09 Python
Python多线程处理实例详解【单进程/多进程】
2019/01/30 Python
python获取点击的坐标画图形的方法
2019/07/09 Python
GWT (Google Web Toolkit)有哪些主要的原件组成?
2015/06/08 面试题
一年级语文教学反思
2014/02/13 职场文书
行政秘书工作自我鉴定
2014/09/15 职场文书
我的中国梦主题教育活动总结
2015/05/07 职场文书
2015年小学语文工作总结
2015/05/25 职场文书
宾馆客房管理制度
2015/08/06 职场文书
初中团委工作总结
2015/08/13 职场文书
小学秋季运动会加油口号及加油稿
2019/08/19 职场文书
基于Golang 高并发问题的解决方案
2021/05/08 Golang
web前端之css水平居中代码解析
2021/05/20 HTML / CSS
Python超详细分步解析随机漫步
2022/03/17 Python
详解Spring Security中的HttpBasic登录验证模式
2022/03/17 Java/Android