自适应线性神经网络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两种遍历字典(dict)的方法比较
May 29 Python
python中列表元素连接方法join用法实例
Apr 07 Python
深入讲解Python编程中的字符串
Oct 14 Python
Python两个内置函数 locals 和globals(学习笔记)
Aug 28 Python
python实现播放音频和录音功能示例代码
Dec 30 Python
python学习--使用QQ邮箱发送邮件代码实例
Apr 16 Python
Python除法之传统除法、Floor除法及真除法实例详解
May 23 Python
Pyqt清空某一个QTreeewidgetItem下的所有分支方法
Jun 17 Python
python 实现手机自动拨打电话的方法(通话压力测试)
Aug 08 Python
python线程优先级队列知识点总结
Feb 28 Python
pytorch 实现L2和L1正则化regularization的操作
Mar 03 Python
PyTorch的Debug指南
May 07 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读取二进制流(C语言结构体struct数据文件)的深入解析
2013/06/13 PHP
php比较两个字符串长度的方法
2015/07/13 PHP
php如何修改SESSION的生存存储时间的实例代码
2017/07/05 PHP
Laravel (Lumen) 解决JWT-Auth刷新token的问题
2019/10/24 PHP
重载toString实现JS HashMap分析
2011/03/13 Javascript
最新的10款jQuery内容滑块插件分享
2011/09/18 Javascript
JS/FLASH实现复制代码到剪贴板(兼容所有浏览器)
2013/05/27 Javascript
javascript实现动态改变层大小的方法
2015/05/14 Javascript
js图片轮播特效代码分享
2015/09/07 Javascript
JS实现简单的二维矩阵乘积运算
2016/01/26 Javascript
Angularjs过滤器使用详解
2016/05/25 Javascript
JavaScript解八皇后问题的方法总结
2016/06/12 Javascript
JS实现的图片预览插件与用法示例【不上传图片】
2016/11/25 Javascript
微信小程序 页面跳转传递值几种方法详解
2017/01/12 Javascript
基于ES6 Array.of的用法(实例讲解)
2017/09/05 Javascript
vue中子组件的methods中获取到props中的值方法
2018/08/27 Javascript
微信小程序配置服务器提示验证token失败的解决方法
2019/04/03 Javascript
详解如何探测小程序返回到webview页面
2019/05/14 Javascript
JQuery常见节点操作实例分析
2019/05/15 jQuery
python使用分治法实现求解最大值的方法
2015/05/12 Python
Python判断文件或文件夹是否存在的三种方法
2017/07/27 Python
解决tensorflow训练时内存持续增加并占满的问题
2020/01/19 Python
python爬取天气数据的实例详解
2020/11/20 Python
python 基于DDT实现数据驱动测试
2021/02/18 Python
Web前端绘制0.5像素的几种方法
2017/08/11 HTML / CSS
猫途鹰英国网站:TripAdvisor英国(旅游社区和旅游评论)
2016/08/30 全球购物
Vision Direct比利时:在线订购隐形眼镜
2019/08/27 全球购物
新员工培训个人的自我评价
2013/10/09 职场文书
微信营销策划方案
2014/02/24 职场文书
节约用水倡议书
2014/04/16 职场文书
英语系本科生求职信
2014/07/15 职场文书
活动主持人开场白
2015/05/28 职场文书
2016年中秋节寄语大全
2015/12/07 职场文书
python实现简单的名片管理系统
2021/04/26 Python
Pytest中conftest.py的用法
2021/06/27 Python
使用kubeadm命令行工具创建kubernetes集群
2022/03/31 Servers