自适应线性神经网络Adaline的python实现详解

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

相对于感知器,采用了f(z)=z的激活函数,属于连续函数。

代价函数为LMS函数,最小均方算法,Least mean square。

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

'''
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();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Python使用numpy实现BP神经网络

    本文完全利用numpy实现一个简单的BP神经网络,由于是做regression而不是classification,因此在这里输出层选取的激励函数就是f(x)=x.BP神经网络的具体原理此处不再介绍. import numpy as np class NeuralNetwork(object): def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # Set number of nodes in i

  • Python实现的径向基(RBF)神经网络示例

    本文实例讲述了Python实现的径向基(RBF)神经网络.分享给大家供大家参考,具体如下: from numpy import array, append, vstack, transpose, reshape, \ dot, true_divide, mean, exp, sqrt, log, \ loadtxt, savetxt, zeros, frombuffer from numpy.linalg import norm, lstsq from multiprocessing impor

  • 神经网络(BP)算法Python实现及应用

    本文实例为大家分享了Python实现神经网络算法及应用的具体代码,供大家参考,具体内容如下 首先用Python实现简单地神经网络算法: import numpy as np # 定义tanh函数 def tanh(x): return np.tanh(x) # tanh函数的导数 def tan_deriv(x): return 1.0 - np.tanh(x) * np.tan(x) # sigmoid函数 def logistic(x): return 1 / (1 + np.exp(-x)

  • Python实现的NN神经网络算法完整示例

    本文实例讲述了Python实现的NN神经网络算法.分享给大家供大家参考,具体如下: 参考自Github开源代码:https://github.com/dennybritz/nn-from-scratch 运行环境 Pyhton3 numpy(科学计算包) matplotlib(画图所需,不画图可不必) sklearn(人工智能包,生成数据使用) 计算过程 输入样例 none 代码实现 # -*- coding:utf-8 -*- #!python3 __author__ = 'Wsine' im

  • Python编程实现的简单神经网络算法示例

    本文实例讲述了Python编程实现的简单神经网络算法.分享给大家供大家参考,具体如下: python实现二层神经网络 包括输入层和输出层 # -*- coding:utf-8 -*- #! python2 import numpy as np #sigmoid function def nonlin(x, deriv = False): if(deriv == True): return x*(1-x) return 1/(1+np.exp(-x)) #input dataset x = np.

  • python构建深度神经网络(DNN)

    本文学习Neural Networks and Deep Learning 在线免费书籍,用python构建神经网络识别手写体的一个总结. 代码主要包括两三部分: 1).数据调用和预处理 2).神经网络类构建和方法建立 3).代码测试文件 1)数据调用: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017-03-12 15:11 # @Author : CC # @File : net_load_data.py # @Soft

  • 基于python神经卷积网络的人脸识别

    本文实例为大家分享了基于神经卷积网络的人脸识别,供大家参考,具体内容如下 1.人脸识别整体设计方案 客_服交互流程图: 2.服务端代码展示 sk = socket.socket() # s.bind(address) 将套接字绑定到地址.在AF_INET下,以元组(host,port)的形式表示地址. sk.bind(("172.29.25.11",8007)) # 开始监听传入连接. sk.listen(True) while True: for i in range(100): #

  • 自适应线性神经网络Adaline的python实现详解

    自适应线性神经网络Adaptive linear network, 是神经网络的入门级别网络. 相对于感知器,采用了f(z)=z的激活函数,属于连续函数. 代价函数为LMS函数,最小均方算法,Least mean square. 实现上,采用随机梯度下降,由于更新的随机性,运行多次结果是不同的. ''' Adaline classifier created on 2019.9.14 author: vince ''' import pandas import math import numpy

  • 神经网络理论基础及Python实现详解

    一.多层前向神经网络 多层前向神经网络由三部分组成:输出层.隐藏层.输出层,每层由单元组成: 输入层由训练集的实例特征向量传入,经过连接结点的权重传入下一层,前一层的输出是下一层的输入:隐藏层的个数是任意的,输入层只有一层,输出层也只有一层: 除去输入层之外,隐藏层和输出层的层数和为n,则该神经网络称为n层神经网络,如下图为2层的神经网络: 一层中加权求和,根据非线性方程进行转化输出:理论上,如果有足够多的隐藏层和足够大的训练集,可以模拟出任何方程: 二.设计神经网络结构 使用神经网络之前,必须

  • python神经网络ResNet50模型的复现详解

    目录 什么是残差网络 什么是ResNet50模型 ResNet50网络部分实现代码 图片预测 什么是残差网络 最近看yolo3里面讲到了残差网络,对这个网络结构很感兴趣,于是了解到这个网络结构最初的使用是在ResNet网络里. Residual net(残差网络): 将靠前若干层的某一层数据输出直接跳过多层引入到后面数据层的输入部分. 意味着后面的特征层的内容会有一部分由其前面的某一层线性贡献. 其结构如下: 深度残差网络的设计是为了克服由于网络深度加深而产生的学习效率变低与准确率无法有效提升的

  • python神经网络Batch Normalization底层原理详解

    目录 什么是Batch Normalization Batch Normalization的计算公式 Bn层的好处 为什么要引入γ和β变量 Bn层的代码实现 什么是Batch Normalization Batch Normalization是神经网络中常用的层,解决了很多深度学习中遇到的问题,我们一起来学习一哈. Batch Normalization是由google提出的一种训练优化方法.参考论文:Batch Normalization Accelerating Deep Network T

  • Python机器学习应用之基于线性判别模型的分类篇详解

    目录 一.Introduction 1 LDA的优点 2 LDA的缺点 3 LDA在模式识别领域与自然语言处理领域的区别 二.Demo 三.基于LDA 手写数字的分类 四.小结 一.Introduction 线性判别模型(LDA)在模式识别领域(比如人脸识别等图形图像识别领域)中有非常广泛的应用.LDA是一种监督学习的降维技术,也就是说它的数据集的每个样本是有类别输出的.这点和PCA不同.PCA是不考虑样本类别输出的无监督降维技术. LDA的思想可以用一句话概括,就是"投影后类内方差最小,类间方

  • python神经网络MobileNet模型的复现详解

    目录 什么是MobileNet模型 MobileNet网络部分实现代码 图片预测 什么是MobileNet模型 MobileNet是一种轻量级网络,相比于其它结构网络,它不一定是最准的,但是它真的很轻 MobileNet模型是Google针对手机等嵌入式设备提出的一种轻量级的深层神经网络,其使用的核心思想便是depthwise separable convolution. 对于一个卷积点而言: 假设有一个3×3大小的卷积层,其输入通道为16.输出通道为32.具体为,32个3×3大小的卷积核会遍历

  • python神经网络MobileNetV2模型的复现详解

    目录 什么是MobileNetV2模型 MobileNetV2网络部分实现代码 图片预测 什么是MobileNetV2模型 MobileNet它哥MobileNetV2也是很不错的呢 MobileNet模型是Google针对手机等嵌入式设备提出的一种轻量级的深层神经网络,其使用的核心思想便是depthwise separable convolution. MobileNetV2是MobileNet的升级版,它具有两个特征点: 1.Inverted residuals,在ResNet50里我们认识

  • python神经网络Inception ResnetV2模型复现详解

    目录 什么是Inception ResnetV2 Inception-ResNetV2的网络结构 1.Stem的结构: 2.Inception-resnet-A的结构: 3.Inception-resnet-B的结构: 4.Inception-resnet-C的结构: 全部代码 什么是Inception ResnetV2 Inception ResnetV2是Inception ResnetV1的一个加强版,两者的结构差距不大,如果大家想了解Inception ResnetV1可以看一下我的另一

  • Python线性表种的单链表详解

    目录 1. 线性表简介 2. 数组 3. 单向链表 设计链表的实现 链表与顺序表的对比 1. 线性表简介 线性表是一种线性结构,它是由零个或多个数据元素构成的有限序列.线性表的特征是在一个序列中,除了头尾元素,每个元素都有且只有一个直接前驱,有且只有一个直接后继,而序列头元素没有直接前驱,序列尾元素没有直接后继. 数据结构中常见的线性结构有数组.单链表.双链表.循环链表等.线性表中的元素为某种相同的抽象数据类型.可以是C语言的内置类型或结构体,也可以是C++自定义类型. 2. 数组 数组在实际的

  • 关于pytorch中全连接神经网络搭建两种模式详解

    pytorch搭建神经网络是很简单明了的,这里介绍两种自己常用的搭建模式: import torch import torch.nn as nn first: class NN(nn.Module): def __init__(self): super(NN,self).__init__() self.model=nn.Sequential( nn.Linear(30,40), nn.ReLU(), nn.Linear(40,60), nn.Tanh(), nn.Linear(60,10), n

随机推荐