自适应线性神经网络Adaptive linear network, 是神经网络的入门级别网络。

相对于感知器,

  1. 采用了f(z)=z的激活函数,属于连续函数。
  2. 代价函数为LMS函数,最小均方算法,Least mean square。

实现上,采用随机梯度下降,由于更新的随机性,运行多次结果是不同的。

  1. '''
  2. Adaline classifier
  3.  
  4. created on 2019.9.14
  5. author: vince
  6. '''
  7. import pandas
  8. import math
  9. import numpy
  10. import logging
  11. import random
  12. import matplotlib.pyplot as plt
  13.  
  14. from sklearn.datasets import load_iris
  15. from sklearn.model_selection import train_test_split
  16. from sklearn.metrics import accuracy_score
  17.  
  18. '''
  19. Adaline classifier
  20.  
  21. Attributes
  22. w: ld-array = weights after training
  23. l: list = number of misclassification during each iteration
  24. '''
  25. class Adaline:
  26. def __init__(self, eta = 0.001, iter_num = 500, batch_size = 1):
  27. '''
  28. eta: float = learning rate (between 0.0 and 1.0).
  29. iter_num: int = iteration over the training dataset.
  30. batch_size: int = gradient descent batch number,
  31. if batch_size == 1, used SGD;
  32. if batch_size == 0, use BGD;
  33. else MBGD;
  34. '''
  35.  
  36. self.eta = eta;
  37. self.iter_num = iter_num;
  38. self.batch_size = batch_size;
  39.  
  40. def train(self, X, Y):
  41. '''
  42. train training data.
  43. X:{array-like}, shape=[n_samples, n_features] = Training vectors,
  44. where n_samples is the number of training samples and
  45. n_features is the number of features.
  46. Y:{array-like}, share=[n_samples] = traget values.
  47. '''
  48. self.w = numpy.zeros(1 + X.shape[1]);
  49. self.l = numpy.zeros(self.iter_num);
  50. for iter_index in range(self.iter_num):
  51. for rand_time in range(X.shape[0]):
  52. sample_index = random.randint(0, X.shape[0] - 1);
  53. if (self.activation(X[sample_index]) == Y[sample_index]):
  54. continue;
  55. output = self.net_input(X[sample_index]);
  56. errors = Y[sample_index] - output;
  57. self.w[0] += self.eta * errors;
  58. self.w[1:] += self.eta * numpy.dot(errors, X[sample_index]);
  59. break;
  60. for sample_index in range(X.shape[0]):
  61. self.l[iter_index] += (Y[sample_index] - self.net_input(X[sample_index])) ** 2 * 0.5;
  62. logging.info("iter %s: w0(%s), w1(%s), w2(%s), l(%s)" %
  63. (iter_index, self.w[0], self.w[1], self.w[2], self.l[iter_index]));
  64. if iter_index > 1 and math.fabs(self.l[iter_index - 1] - self.l[iter_index]) < 0.0001:
  65. break;
  66.  
  67. def activation(self, x):
  68. return numpy.where(self.net_input(x) >= 0.0 , 1 , -1);
  69.  
  70. def net_input(self, x):
  71. return numpy.dot(x, self.w[1:]) + self.w[0];
  72.  
  73. def predict(self, x):
  74. return self.activation(x);
  75.  
  76. def main():
  77. logging.basicConfig(level = logging.INFO,
  78. format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
  79. datefmt = '%a, %d %b %Y %H:%M:%S');
  80.  
  81. iris = load_iris();
  82.  
  83. features = iris.data[:99, [0, 2]];
  84. # normalization
  85. features_std = numpy.copy(features);
  86. for i in range(features.shape[1]):
  87. features_std[:, i] = (features_std[:, i] - features[:, i].mean()) / features[:, i].std();
  88.  
  89. labels = numpy.where(iris.target[:99] == 0, -1, 1);
  90.  
  91. # 2/3 data from training, 1/3 data for testing
  92. train_features, test_features, train_labels, test_labels = train_test_split(
  93. features_std, labels, test_size = 0.33, random_state = 23323);
  94.  
  95. logging.info("train set shape:%s" % (str(train_features.shape)));
  96.  
  97. classifier = Adaline();
  98.  
  99. classifier.train(train_features, train_labels);
  100.  
  101. test_predict = numpy.array([]);
  102. for feature in test_features:
  103. predict_label = classifier.predict(feature);
  104. test_predict = numpy.append(test_predict, predict_label);
  105.  
  106. score = accuracy_score(test_labels, test_predict);
  107. logging.info("The accruacy score is: %s "% (str(score)));
  108.  
  109. #plot
  110. x_min, x_max = train_features[:, 0].min() - 1, train_features[:, 0].max() + 1;
  111. y_min, y_max = train_features[:, 1].min() - 1, train_features[:, 1].max() + 1;
  112. plt.xlim(x_min, x_max);
  113. plt.ylim(y_min, y_max);
  114. plt.xlabel("width");
  115. plt.ylabel("heigt");
  116.  
  117. plt.scatter(train_features[:, 0], train_features[:, 1], c = train_labels, marker = 'o', s = 10);
  118.  
  119. k = - classifier.w[1] / classifier.w[2];
  120. d = - classifier.w[0] / classifier.w[2];
  121.  
  122. plt.plot([x_min, x_max], [k * x_min + d, k * x_max + d], "go-");
  123.  
  124. plt.show();
  125.  
  126. if __name__ == "__main__":
  127. main();

自适应线性神经网络Adaline的更多相关文章

  1. python机器学习——自适应线性神经元

    上篇博客我们说了感知器,这篇博客主要记录自适应线性神经元的实现算法及一些其他的训练细节,自适应线性神经元(简称为Adaline)由Bernard Widrow和他的博士生Tedd Hoff提出,对感知 ...

  2. 神经网络_线性神经网络 2 (Nerual Network_Linear Nerual Network 2)

    1 LMS 学习规则 1.1 LMS学习规则定义 MSE=(1/Q)*Σe2k=(1/Q)*Σ(tk-ak)2,k=1,2,...,Q 式中:Q是训练样本:t(k)是神经元的期望输出:a(k)是神经元 ...

  3. 神经网络_线性神经网络 1 (Nerual Network_Linear Nerual Network 1)

    2019-04-08 16:59:23 1 学习规则(Learning Rule) 1.1 赫布学习规则(Hebb Learning Rule) 1949年,Hebb提出了关于神经网络学习机理的“突触 ...

  4. 单层感知机_线性神经网络_BP神经网络

    单层感知机 单层感知机基础总结很详细的博客 关于单层感知机的视频 最终y=t,说明经过训练预测值和真实值一致.下面图是sign函数 根据感知机规则实现的上述题目的代码 import numpy as ...

  5. 使用MindSpore的线性神经网络拟合非线性函数

    技术背景 在前面的几篇博客中,我们分别介绍了MindSpore的CPU版本在Docker下的安装与配置方案.MindSpore的线性函数拟合以及MindSpore后来新推出的GPU版本的Docker编 ...

  6. MATLAB——线性神经网络

     这个函数默认使用最小二乘,所以不需要训练 % example5_1.m x=-:; y=*x-; % 直线方程为 randn(); % 设置种子,便于重复执行 y=y+randn(,length(y ...

  7. 神经网络_线性神经网络 3 (Nerual Network_Linear Nerual Network 3)

    1 LMS 学习规则_解方程组 1.1 LMS学习规则举例 X1=[0 0 1]T,t1=0:X2=[1 0 1]T,t2=0:X3=[0 1 1]T,t3=0:X1=[1 1 1]T,t1=1. 设 ...

  8. (转)神经网络和深度学习简史(第一部分):从感知机到BP算法

    深度|神经网络和深度学习简史(第一部分):从感知机到BP算法 2016-01-23 机器之心 来自Andrey Kurenkov 作者:Andrey Kurenkov 机器之心编译出品 参与:chen ...

  9. 机器学习 —— 基础整理(六)线性判别函数:感知器、松弛算法、Ho-Kashyap算法

    这篇总结继续复习分类问题.本文简单整理了以下内容: (一)线性判别函数与广义线性判别函数 (二)感知器 (三)松弛算法 (四)Ho-Kashyap算法 闲话:本篇是本系列[机器学习基础整理]在time ...

随机推荐

  1. 优秀的Spring Cloud开源项目整理推荐

    无论是对于初学者,还是有一定工作经验的程序员来讲,Spring Cloud开源项目都是一笔宝贵的财富.下面给大家整理了十个优秀的开源项目,分别是spring-cloud-examples.spaasc ...

  2. jvm的运行参数

    1.我们为什么要对jvm做优化? 在本地开发环境中我们很少会遇到需要对jvm进行优化的需求,但是到了生产环境,我们可能将有下面的需求: 运行的应用“卡住了”,日志不输出,程序没有反应 服务器的CPU负 ...

  3. LeetCode python实现题解(持续更新)

    目录 LeetCode Python实现算法简介 0001 两数之和 0002 两数相加 0003 无重复字符的最长子串 0004 寻找两个有序数组的中位数 0005 最长回文子串 0006 Z字型变 ...

  4. 使用HBuilder开发移动APP

    前言 HBuilder是DCloud(数字天堂)推出的一款支持HTML5的Web开发IDE.HBuilder的编写用到了Java.C.Web和Ruby.HBuilder本身主体是由Java编写,它基于 ...

  5. python+opencv->边缘提取与各函数参数解析

    前情提要:作为刚入门机器视觉的小伙伴,第一节课学到机器视觉语法时觉得很难理解, 很多人家的经验,我发现都千篇一律,功能函数没解析,参数不讲解,就一个代码,所以在此将搜集的解析和案例拿出来汇总!!! 一 ...

  6. 3DGIS+BIM集成与智慧城市应用

    ZTMap3D是基于网络的三维地理信息系统平台软件,利用 ZTMap3D能够实现三维地理信息和虚拟现实,是数字化地球和数字化城市建设的基础平台. BIM(building information mo ...

  7. 用反射机制和pandas,实现excel数据的读取以及参数化${arg}的赋值

    反射类:class GetData: index = pd.read_excel(file_name, sheet_name).loc[0, ['index']].values[0] email = ...

  8. Thread同步

    今天本人给大家讲解一下多线程的线程同步,如有不对的或者讲的不好的可以多多提出,我会进行相应的更改,先提前感谢提出意见的各位了!!! 开始说线程同步前先来个小案例: 案例启:所有的类都在Demo01中, ...

  9. Mathtype快捷键&小技巧

    Mathtype使用方便,能插入到Office等编辑器中,Latex公式在某些地方更加通用,如网页和书籍. 1. Mathtype简介 数学公式编辑器(MathType)是一款专业的数学公式编辑工具, ...

  10. .NET写入文件操作

    2018-01-16  22:44:35 许多程序需要记录运行日志,这就需要将程序运行记录写入本机,一般是.txt 文本或.csv 文件.具体操作如下: 一.C#   using System.IO; ...