自适应线性神经网络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多线程编程(二):启动线程的两种方法
Apr 05 Python
利用python批量检查网站的可用性
Sep 09 Python
利用python发送和接收邮件
Sep 27 Python
python实现kNN算法
Dec 20 Python
python使用pycharm环境调用opencv库
Feb 11 Python
解决Pycharm界面的子窗口不见了的问题
Jan 17 Python
python防止随意修改类属性的实现方法
Aug 21 Python
Python 中@property的用法详解
Jan 15 Python
Python Tornado批量上传图片并显示功能
Mar 26 Python
python使用梯度下降和牛顿法寻找Rosenbrock函数最小值实例
Apr 02 Python
深入理解python多线程编程
Apr 18 Python
python使用torch随机初始化参数
Mar 22 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中截取中文字符串的代码小结
2011/07/17 PHP
Zend Framework入门教程之Zend_Config组件用法详解
2016/12/09 PHP
PHP DB 数据库连接类定义与用法示例
2019/03/11 PHP
js中scrollHeight,scrollWidth,scrollLeft,scrolltop等差别介绍
2012/05/16 Javascript
JSON辅助格式化处理方法
2013/03/26 Javascript
jquery常用特效方法使用示例
2014/04/25 Javascript
基于jQuery实现表格内容的筛选功能
2016/08/21 Javascript
ng2学习笔记之bootstrap中的component使用教程
2017/03/09 Javascript
详解如何在Vue2中实现组件props双向绑定
2017/03/29 Javascript
jQuery开源组件BootstrapValidator使用详解
2017/06/29 jQuery
JS小球抛物线轨迹运动的两种实现方法详解
2017/12/20 Javascript
深入浅析Vue中的 computed 和 watch
2018/06/06 Javascript
Webpack 4.x搭建react开发环境的方法步骤
2018/08/15 Javascript
JavaScript中构造函数与原型链之间的关系详解
2019/02/25 Javascript
NodeJs crypto加密制作token的实现代码
2019/11/15 NodeJs
如何用vue-cli3脚手架搭建一个基于ts的基础脚手架的方法
2019/12/12 Javascript
Vue移动端用淘宝弹性布局lib-flexible插件做适配的方法
2020/05/26 Javascript
[01:23]2014DOTA2国际邀请赛 球迷无处不在Ti现场世界杯受关注
2014/07/10 DOTA
python抓取豆瓣图片并自动保存示例学习
2014/01/10 Python
Python使用ftplib实现简易FTP客户端的方法
2015/06/03 Python
利用python程序生成word和PDF文档的方法
2017/02/14 Python
Python中单、双下划线的区别总结
2017/12/01 Python
python利用插值法对折线进行平滑曲线处理
2018/12/25 Python
Python面向对象类编写细节分析【类,方法,继承,超类,接口等】
2019/01/05 Python
python与mysql数据库交互的实现
2020/01/06 Python
python实现高斯投影正反算方式
2020/01/17 Python
python GUI库图形界面开发之PyQt5信号与槽机制、自定义信号基础介绍
2020/02/25 Python
Python Socket TCP双端聊天功能实现过程详解
2020/06/15 Python
python 解决selenium 中的 .clear()方法失效问题
2020/09/01 Python
Python+OpenCV图像处理——图像二值化的实现
2020/10/24 Python
大学毕业的自我鉴定
2013/10/08 职场文书
《开国大典》教学反思
2014/04/19 职场文书
公务员考察材料
2014/12/23 职场文书
python中对列表的删除和添加方法详解
2022/02/24 Python
python的netCDF4批量处理NC格式文件的操作方法
2022/03/21 Python
MySQL添加索引特点及优化问题
2022/07/23 MySQL