自适应线性神经网络Adaline的python实现详解


Posted in Python onSeptember 30, 2019

自适应线性神经网络Adaptive linear network, 是神经网络的入门级别网络。

相对于感知器,采用了f(z)=z的激活函数,属于连续函数。

代价函数为LMS函数,最小均方算法,Least mean square。

自适应线性神经网络Adaline的python实现详解

实现上,采用随机梯度下降,由于更新的随机性,运行多次结果是不同的。

'''
Adaline classifier

created on 2019.9.14
author: vince
'''
import pandas 
import math
import numpy 
import logging
import random
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

'''
Adaline classifier

Attributes
w: ld-array = weights after training
l: list = number of misclassification during each iteration 
'''
class Adaline:
  def __init__(self, eta = 0.001, iter_num = 500, 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 rand_time in range(X.shape[0]): 
        sample_index = random.randint(0, X.shape[0] - 1);
        if (self.activation(X[sample_index]) == Y[sample_index]):
          continue;
        output = self.net_input(X[sample_index]);
        errors = Y[sample_index] - output;
        self.w[0] += self.eta * errors;
        self.w[1:] += self.eta * numpy.dot(errors, X[sample_index]);
        break;
      for sample_index in range(X.shape[0]): 
        self.l[iter_index] += (Y[sample_index] - self.net_input(X[sample_index])) ** 2 * 0.5;
      logging.info("iter %s: w0(%s), w1(%s), w2(%s), l(%s)" %
          (iter_index, self.w[0], self.w[1], self.w[2], self.l[iter_index]));
      if iter_index > 1 and math.fabs(self.l[iter_index - 1] - self.l[iter_index]) < 0.0001: 
        break;

  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)));

  classifier = Adaline();

  classifier.train(train_features, train_labels);
    
  test_predict = numpy.array([]);
  for feature in test_features:
    predict_label = classifier.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 = - classifier.w[1] / classifier.w[2];
  d = - classifier.w[0] / classifier.w[2];

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

  plt.show();
  

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

自适应线性神经网络Adaline的python实现详解

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

Python 相关文章推荐
Python写的Tkinter程序屏幕居中方法
Mar 10 Python
Python实现保证只能运行一个脚本实例
Jun 24 Python
python 网络编程常用代码段
Aug 28 Python
Python字符串格式化的方法(两种)
Sep 19 Python
python的sorted用法详解
Jun 25 Python
keras自定义回调函数查看训练的loss和accuracy方式
May 23 Python
Python 程序员必须掌握的日志记录
Aug 17 Python
Windows下pycharm安装第三方库失败(通用解决方案)
Sep 17 Python
python SOCKET编程基础入门
Feb 27 Python
Python生成九宫格图片的示例代码
Apr 14 Python
python调试工具Birdseye的使用教程
May 25 Python
关于的python五子棋的算法
May 02 Python
softmax及python实现过程解析
Sep 30 #Python
python根据时间获取周数代码实例
Sep 30 #Python
Win10 安装PyCharm2019.1.1(图文教程)
Sep 29 #Python
PyCharm2019安装教程及其使用(图文教程)
Sep 29 #Python
Python 文件操作之读取文件(read),文件指针与写入文件(write),文件打开方式示例
Sep 29 #Python
python3.7 利用函数os pandas利用excel对文件名进行归类
Sep 29 #Python
Python 多线程,threading模块,创建子线程的两种方式示例
Sep 29 #Python
You might like
Php图像处理类代码分享
2012/01/19 PHP
php警告Creating default object from empty value 问题的解决方法
2014/04/02 PHP
php获取网页上所有链接的方法
2015/04/03 PHP
php+ajax 文件上传代码实例
2019/03/18 PHP
PHP cookie,session的使用与用户自动登录功能实现方法分析
2019/06/05 PHP
基于jQuery的投票系统显示结果插件
2011/08/12 Javascript
jBox 2.3基于jquery的最新多功能对话框插件 常见使用问题解答
2011/11/10 Javascript
Jquery修改页面标题title其它JS失效的解决方法
2014/10/31 Javascript
用JavaScript实现对话框的教程
2015/06/04 Javascript
javascript中$(function() {});写与不写有哪些区别
2015/08/10 Javascript
浅谈JavaScript中的对象及Promise对象的实现
2015/11/15 Javascript
详解JavaScript语言的基本语法要求
2015/11/20 Javascript
jQuery自定义动画函数实例详解(附demo源码)
2015/12/10 Javascript
jQuery插件实现表格隔行变色及鼠标滑过高亮显示效果代码
2016/02/25 Javascript
使用bootstrap3开发响应式网站
2016/05/12 Javascript
javascript 广告移动特效的实现代码
2016/06/25 Javascript
jQuery中checkbox反复调用attr('checked', true/false)只有第一次生效的解决方法
2016/11/16 Javascript
Vue完整项目构建(进阶篇)
2018/02/10 Javascript
angularJs select绑定的model取不到值的解决方法
2018/10/08 Javascript
详解React服务端渲染从入门到精通
2019/03/28 Javascript
通过循环优化 JavaScript 程序
2019/06/24 Javascript
[00:33]2018DOTA2亚洲邀请赛TNC出场
2018/04/04 DOTA
Python实现的tab文件操作类分享
2014/11/20 Python
Python数据类型详解(一)字符串
2016/05/08 Python
Python使用Pycrypto库进行RSA加密的方法详解
2016/06/06 Python
Python实现的调用C语言函数功能简单实例
2019/03/13 Python
Pandas读写CSV文件的方法示例
2019/03/27 Python
Python安装与卸载流程详细步骤(图解)
2020/02/20 Python
Python3如何实现Win10桌面自动切换
2020/08/11 Python
详解pytorch tensor和ndarray转换相关总结
2020/09/03 Python
Pandas直接读取sql脚本的方法
2021/01/21 Python
英国男女豪华配饰和礼品网站:Black.co.uk
2020/02/28 全球购物
中学生差生评语
2014/01/30 职场文书
实习指导老师评语
2014/04/26 职场文书
大学生交通专业求职信
2014/09/01 职场文书
2019送给家人们的中秋节祝福语
2019/08/15 职场文书