自适应线性神经网络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写的windows服务不能启动的问题
Apr 15 Python
Python实现多行注释的另类方法
Aug 22 Python
详解Python的Django框架中manage命令的使用与扩展
Apr 11 Python
Python单链表简单实现代码
Apr 27 Python
Python实现的概率分布运算操作示例
Aug 14 Python
利用TensorFlow训练简单的二分类神经网络模型的方法
Mar 05 Python
对tf.reduce_sum tensorflow维度上的操作详解
Jul 26 Python
python字典一键多值实例代码分享
Jun 14 Python
PyQt5中向单元格添加控件的方法示例
Mar 24 Python
Django通过json格式收集主机信息
May 29 Python
python中_del_还原数据的方法
Dec 09 Python
使用Python开发冰球小游戏
Apr 30 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 无限极分类
2008/03/27 PHP
php实现的百度搜索某地天气的小偷代码
2014/04/23 PHP
PHP中使用数组指针函数操作数组示例
2014/11/19 PHP
浅谈PHP中单引号和双引号到底有啥区别呢?
2015/03/04 PHP
php获取错误信息的方法
2015/07/17 PHP
php文件上传的两种实现方法
2016/04/04 PHP
ThinkPHP5 验证器的具体使用
2018/05/31 PHP
PHP操作路由器实现方法示例
2019/04/27 PHP
jquery插件 autoComboBox 下拉框
2010/12/22 Javascript
JavaScript处理解析JSON数据过程详解
2015/09/11 Javascript
基于vue监听滚动事件实现锚点链接平滑滚动的方法
2018/01/17 Javascript
React native ListView 增加顶部下拉刷新和底下点击刷新示例
2018/04/27 Javascript
vue实现输入框的模糊查询的示例代码(节流函数的应用场景)
2019/09/01 Javascript
jquery将json转为数据字典的实例代码
2019/10/11 jQuery
jQuery实现轮播图效果
2019/11/26 jQuery
JavaScript或jQuery 获取option value值方法解析
2020/05/12 jQuery
[01:03:13]VG vs Pain 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
python先序遍历二叉树问题
2017/11/10 Python
基于python requests库中的代理实例讲解
2018/05/07 Python
详解利用python+opencv识别图片中的圆形(霍夫变换)
2019/07/01 Python
python删除列表元素的三种方法(remove,pop,del)
2019/07/22 Python
python用类实现文章敏感词的过滤方法示例
2019/10/27 Python
logging level级别介绍
2020/02/21 Python
Python自动化办公Excel模块openpyxl原理及用法解析
2020/11/05 Python
python3中calendar返回某一时间点实例讲解
2020/11/18 Python
ET Mall东森购物网:东森严选
2017/03/06 全球购物
GANT葡萄牙官方商店:拥有美国运动服传统的生活方式品牌
2018/10/18 全球购物
人力资源管理毕业生自荐信
2013/11/21 职场文书
母亲80寿诞答谢词
2014/01/16 职场文书
五一促销活动总结
2014/07/01 职场文书
试用期员工工作自我评价
2014/09/10 职场文书
党员民主生活会对照检查材料思想汇报
2014/09/28 职场文书
2014年预算员工作总结
2014/12/05 职场文书
公司开业的祝贺语大全(60条)
2019/07/05 职场文书
Pytorch 统计模型参数量的操作 param.numel()
2021/05/13 Python
Python 绘制多因子柱状图
2022/05/11 Python