自适应线性神经网络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 相关文章推荐
Python3基础之条件与循环控制实例解析
Aug 13 Python
python使用sorted函数对列表进行排序的方法
Apr 04 Python
Python while、for、生成器、列表推导等语句的执行效率测试
Jun 03 Python
利用Python中unittest实现简单的单元测试实例详解
Jan 09 Python
python使用fork实现守护进程的方法
Nov 16 Python
Python统计单词出现的次数
Apr 04 Python
Python爬虫运用正则表达式的方法和优缺点
Aug 25 Python
python实现两个文件夹的同步
Aug 29 Python
Python 静态方法和类方法实例分析
Nov 21 Python
Python socket处理client连接过程解析
Mar 18 Python
numpy库reshape用法详解
Apr 19 Python
python海龟绘图之画国旗实例代码
Nov 11 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命令空间namespace及use的用法小结
2017/11/27 PHP
thinkPHP3.2.2框架行为扩展及demo示例
2018/06/19 PHP
asp.net+js 实现无刷新上传解析csv文件的代码
2010/05/17 Javascript
jQuery的实现原理的模拟代码 -1 核心部分
2010/08/01 Javascript
jquery加载页面的方法(页面加载完成就执行)
2011/06/21 Javascript
jquery validate 自定义验证方法介绍 日期验证
2014/02/27 Javascript
JQuery表单验证插件EasyValidator用法分析
2014/11/15 Javascript
JavaScript中的Truthy和Falsy介绍
2015/01/01 Javascript
使用jQuery实现更改默认alert框体
2015/04/13 Javascript
jquery Easyui快速开发总结
2015/08/20 Javascript
javascript实现无缝上下滚动特效
2015/12/16 Javascript
点评js异步加载的4种方式
2015/12/22 Javascript
javascript的正则匹配方法学习
2016/02/24 Javascript
jQuery计算文本框字数及限制文本框字数的方法
2016/03/01 Javascript
手机端js和html5刮刮卡效果
2020/09/29 Javascript
vue 请求后台数据的实例代码
2017/06/22 Javascript
关于定制FileField中的上传文件名称问题
2017/08/22 Javascript
使用Python的Bottle框架写一个简单的服务接口的示例
2015/08/25 Python
python入门:这篇文章带你直接学会python
2018/09/14 Python
Python3使用TCP编写一个简易的文件下载器功能
2019/05/08 Python
介绍一款python类型检查工具pyright(推荐)
2019/07/03 Python
python适合做数据挖掘吗
2020/06/16 Python
python进度条显示-tqmd模块的实现示例
2020/08/23 Python
Django web自定义通用权限控制实现方法
2020/11/24 Python
Python3爬虫RedisDump的安装步骤
2021/02/20 Python
家长会学生家长演讲稿
2013/12/29 职场文书
教师批评与自我批评总结
2014/10/16 职场文书
教师自查自纠工作情况报告
2014/10/29 职场文书
三年级学生期末评语
2014/12/26 职场文书
小学教师个人工作总结2015
2015/04/20 职场文书
永远是春天观后感
2015/06/12 职场文书
MySQL图形化管理工具Navicat安装步骤
2021/12/04 MySQL
使用Bandicam录制鼠标指针并附带点击声音,还可以添加点击动画效果
2022/04/11 数码科技
oracle数据库去除重复数据
2022/05/20 Oracle
Java处理延时任务的常用几种解决方案
2022/06/01 Java/Android
python缺失值填充方法示例代码
2022/12/24 Python