自适应线性神经网络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 相关文章推荐
在Django的URLconf中使用多个视图前缀的方法
Jul 18 Python
python根据京东商品url获取产品价格
Aug 09 Python
Python发送form-data请求及拼接form-data内容的方法
Mar 05 Python
Python 3中的yield from语法详解
Jan 18 Python
Python中字典(dict)合并的四种方法总结
Aug 10 Python
浅析python协程相关概念
Jan 20 Python
TensorFlow实现iris数据集线性回归
Sep 07 Python
深入解析python中的实例方法、类方法和静态方法
Mar 11 Python
Python 保持登录状态进行接口测试的方法示例
Aug 06 Python
Python ckeditor富文本编辑器代码实例解析
Jun 22 Python
基于Python实现下载网易音乐代码实例
Aug 10 Python
实现Python3数组旋转的3种算法实例
Sep 16 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
用PHP4访问Oracle815
2006/10/09 PHP
ZF等常用php框架中存在的问题
2008/01/10 PHP
PHP压缩html网页代码(清除空格,换行符,制表符,注释标记)
2012/04/02 PHP
JS异常处理try..catch语句的作用和实例
2014/05/05 PHP
PHP实现的随机IP函数【国内IP段】
2016/07/20 PHP
javascript 树控件 比较好用
2009/06/11 Javascript
javascript不可用的问题探究
2013/10/01 Javascript
用js闭包的方法实现多点标注冒泡示例
2014/05/29 Javascript
jQuery EasyUI datagrid在翻页以后仍能记录被选中行的实现代码
2016/08/15 Javascript
Vue数据驱动模拟实现1
2017/01/11 Javascript
switchery按钮的使用方法
2017/12/18 Javascript
vuex + axios 做登录验证 并且保存登录状态的实例
2018/09/16 Javascript
详解微信小程序中组件通讯
2018/10/30 Javascript
JS实现的点击按钮图片上下滚动效果示例
2019/01/28 Javascript
js实现跟随鼠标移动的小球
2019/08/26 Javascript
JS+CSS实现3D切割轮播图
2020/03/21 Javascript
Element实现表格嵌套、多个表格共用一个表头的方法
2020/05/09 Javascript
python3图片转换二进制存入mysql
2013/12/06 Python
Python入门篇之字符串
2014/10/17 Python
一篇文章入门Python生态系统(Python新手入门指导)
2015/12/11 Python
Python3计算三角形的面积代码
2017/12/18 Python
简单了解Pandas缺失值处理方法
2019/11/16 Python
python实现从尾到头打印单链表操作示例
2020/02/22 Python
基于python实现查询ip地址来源
2020/06/02 Python
python 基于pygame实现俄罗斯方块
2021/03/02 Python
利用CSS3的3D效果制作正方体
2020/03/10 HTML / CSS
英国团购网站:Groupon英国
2017/11/28 全球购物
学生就业推荐信
2013/11/13 职场文书
父亲生日宴会答谢词
2014/01/10 职场文书
会议接待欢迎词
2014/01/12 职场文书
教师应聘自荐信范文
2014/03/14 职场文书
保护环境建议书作文300字
2015/09/14 职场文书
房屋买卖定金协议书
2016/03/21 职场文书
将Python代码打包成.exe可执行文件的完整步骤
2021/05/12 Python
教你漂亮打印Pandas DataFrames和Series
2021/05/29 Python
利用Python第三方库实现预测NBA比赛结果
2021/06/21 Python