自适应线性神经网络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修改注册表终止360进程实例
Oct 13 Python
Python中生成器和yield语句的用法详解
Apr 17 Python
python制作最美应用的爬虫
Oct 28 Python
Python3实现带附件的定时发送邮件功能
Dec 22 Python
详解分布式任务队列Celery使用说明
Nov 29 Python
图文详解python安装Scrapy框架步骤
May 20 Python
python实现列表的排序方法分享
Jul 01 Python
在Django model中设置多个字段联合唯一约束的实例
Jul 17 Python
解决Django中修改js css文件但浏览器无法及时与之改变的问题
Aug 31 Python
Python 发送邮件方法总结
Aug 10 Python
详解vscode实现远程linux服务器上Python开发
Nov 10 Python
基于python+selenium自动健康打卡的实现代码
Jan 13 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中删除字符串中最先出现某个字符的实现代码
2013/02/03 PHP
PHP7实现和CryptoJS的AES加密方式互通示例【AES-128-ECB加密】
2019/06/08 PHP
PHP For循环字母A-Z当超过26个字母时输出AA,AB,AC
2020/02/16 PHP
xml和web特殊字符
2009/04/28 Javascript
Javascript简单实现可拖动的div
2013/10/22 Javascript
使用jQuery快速解决input中placeholder值在ie中无法支持的问题
2014/01/02 Javascript
在JS数组特定索引处指定位置插入元素的技巧
2014/08/24 Javascript
javascript中if和switch,==和===详解
2015/07/30 Javascript
jQuery Easyui实现左右布局
2016/01/26 Javascript
JS出现失效的情况总结
2017/01/20 Javascript
AngularJS的ng-repeat指令与scope继承关系实例详解
2017/01/21 Javascript
JS中使用textPath实现线条上的文字
2017/12/25 Javascript
node中modules.exports与exports导出的区别
2018/06/08 Javascript
js for终止循环 跳出多层循环
2018/10/04 Javascript
vue滚动插件better-scroll使用详解
2019/10/18 Javascript
Layui实现主窗口和Iframe层参数传递
2019/11/14 Javascript
javascript中的with语句学习笔记及用法
2020/02/17 Javascript
在vue中使用Echarts画曲线图的示例
2020/10/03 Javascript
详解Vue.js 可拖放文本框组件的使用
2021/03/03 Vue.js
python实现树的深度优先遍历与广度优先遍历详解
2019/10/26 Python
Django框架反向解析操作详解
2019/11/28 Python
jenkins+python自动化测试持续集成教程
2020/05/12 Python
python开发入门——set的使用
2020/09/03 Python
python使用matplotlib绘制折线图的示例代码
2020/09/22 Python
Python如何批量生成和调用变量
2020/11/21 Python
计算机应用专业学生的自我评价分享
2013/11/03 职场文书
服务中心夜班服务员岗位职责
2013/11/27 职场文书
主办会计岗位职责
2014/03/13 职场文书
读书之星事迹材料
2014/05/12 职场文书
学习十八届四中全会精神思想汇报
2014/10/23 职场文书
党员作风建设整改方案
2014/10/27 职场文书
八达岭长城导游词
2015/01/30 职场文书
领导欢送会主持词
2015/07/06 职场文书
《纸船和风筝》教学反思
2016/02/18 职场文书
MySQL锁机制
2021/04/05 MySQL
MySQL索引是啥?不懂就问
2021/07/21 MySQL