We turn next to the task of finding a weight vector w which minimizes the chosen function E(w).

Because there is clearly no hope of finding an anlytical solution to the equation ∂E(w)=0, we resort to

iterative numerical procedures.

On-line gradient descent, also known as sequential gradient descent or stochastic gradient descent, makes

an update to the weight vector based on one data point at a time.

One advantage of on-line methods compared to batch methods is that the former handle redundancy in the data

much more efficiently. Another property of on-line gradient descent is the possibility of escaping from local minima,

since a stationary point with respect to the error function for the whole data set will generally not be a stationary point

for each data point individually.

Another advantage of on-line learning is the fact that it requires much less storage than batch learning.

原始数据获得

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cfloat>
#include <cmath>

double dis(double &train, double &query) {
  double weight=exp(-0.5*pow(train-query, 2));

  return weight;
}

/*最小二乘法*/
template <typename PairIterator>
bool GetLinearFit(PairIterator begin_it, PairIterator end_it, double& slope, double& y_intercept) {
    if(begin_it==end_it) {
        return false;
    }
    size_t n=end_it-begin_it;
    double sum_x2=0.0,sum_y=0.0,sum_x=0.0,sum_xy=0.0;

for(PairIterator it=begin_it;it!=end_it;++it) {
        sum_x2+=(it->first)*(it->first);
        sum_y+=it->second;
        sum_x+=it->first;
        sum_xy+=(it->first)*(it->second);
    }

slope=(n*sum_xy-sum_x*sum_y)/(n*sum_x2-sum_x*sum_x);
    y_intercept=(sum_x2*sum_y-sum_x*sum_xy)/(n*sum_x2-sum_x*sum_x);

return true;
}

/*locally weighted linear regression(LWR)*/
template<typename PairIterator>
bool LWR(PairIterator begin_it, PairIterator end_it, double& slope, double& y_intercept) {
  if(begin_it==end_it) {
    return false;
  }

   /*x are the data points for each local regression model. They are usually (but not always) the data points in your sample.*/
  double query=5.5;
  size_t n=end_it-begin_it;
  double J=0.0;

  for(PairIterator it=begin_it;it!=end_it;++it) {
    J+=(y_intercept+slope*(it->first)-it->second)*(y_intercept+slope*(it->first)-it->second)*dis(it->first, query);
  }
  J=J*0.5/n;

  while(true) {
    double temp0=0,temp1=0;
    for(PairIterator it=begin_it;it!=end_it;++it) {
      temp0+=(y_intercept+slope*(it->first)-it->second)*dis(it->first, query);
      temp1+=(y_intercept+slope*(it->first)-it->second)*(it->first)*dis(it->first, query);
    }

    temp0=temp0/n;
    temp1=temp1/n;

    /*0.03为学习率阿尔法*/
    y_intercept=y_intercept-0.03*temp0;
    slope=slope-0.03*temp1;

    double MSE=0.0;
    for(PairIterator it=begin_it;it!=end_it;++it) {
      MSE+=(y_intercept+slope*(it->first)-it->second)*(y_intercept+slope*(it->first)-it->second)*dis(it->first, query);
    }
    MSE=0.5*MSE/n;
    if(std::abs(J-MSE)<0.00000001)
      break;
    J=MSE;
    }
  return true;
}

/*批量梯度下降法,Batch Gradient Desscent,BGD*/
template<typename PairIterator>
bool BatchGradientDescent(PairIterator begin_it, PairIterator end_it, double& slope, double& y_intercept) {
    if(begin_it==end_it) {
        return false;
    }
    size_t n=end_it-begin_it;
    double J=0.0;

/*the initial cost function*/
    for(PairIterator it=begin_it;it!=end_it;++it) {
        J+=(y_intercept+slope*(it->first)-it->second)*(y_intercept+slope*(it->first)-it->second);
    }
    J=J*0.5/n;

while(true) {
        double temp0=0,temp1=0;
        for(PairIterator it=begin_it;it!=end_it;++it) {
            temp0+=(y_intercept+slope*(it->first)-it->second);
            temp1+=(y_intercept+slope*(it->first)-it->second)*(it->first);
        }
        temp0=temp0/n;
        temp1=temp1/n;

/*0.03为学习率阿尔法*/
        y_intercept=y_intercept-0.03*temp0;
        slope=slope-0.03*temp1;

double MSE=0.0;
        for(PairIterator it=begin_it;it!=end_it;++it) {
            MSE+=(y_intercept+slope*(it->first)-it->second)*(y_intercept+slope*(it->first)-it->second);
        }
        MSE=0.5*MSE/n;
        if(std::abs(J-MSE)<0.00000001)
            break;
        J=MSE;
    }
    return true;
}

/*随机梯度下降法,Stochastic Gradient Desscent,SGD*/
template<typename PairIterator>
bool StochasticGradientDescent(PairIterator begin_it, PairIterator end_it, double& slope, double& y_intercept) {
    if(begin_it==end_it) {
        return false;
    }
    size_t n=end_it-begin_it;
    double J=0.0;

/*the initial cost function*/
    for(PairIterator it=begin_it;it!=end_it;++it) {
        J+=(y_intercept+slope*(it->first)-it->second)*(y_intercept+slope*(it->first)-it->second);
    }
    J=0.5*J/n;

while(true) {
        double temp0=0,temp1=0;
        for(PairIterator it=begin_it;it!=end_it;++it) {
            temp0=(y_intercept+slope*(it->first)-it->second);
            temp1=(y_intercept+slope*(it->first)-it->second)*(it->first);

/*0.03为学习率阿尔法*/
            y_intercept=y_intercept-0.03*temp0;
            slope=slope-0.03*temp1;

double MSE=0.0;
            for(PairIterator it=begin_it;it!=end_it;++it) {
                MSE+=(y_intercept+slope*(it->first)-it->second)*(y_intercept+slope*(it->first)-it->second);
            }
            MSE=0.5*MSE/n;
            if(std::abs(J-MSE)<0.00000001)
                break;
            J=MSE;
        }
        break;
    }

return true;
}

int main() {
    std::ifstream in;
    in.open("ex2x.dat");
    if(!in) {
        std::cout<<"open file ex2x.dat failed!"<<std::endl;
        return 1;
    }

std::vector<double> datax,datay;
    double temp;

while(in>>temp) {
        datax.push_back(temp);
    }

in.close();
    in.open("ex2y.dat");
    if(!in) {
        std::cout<<"open file ex2y.dat failed!"<<std::endl;
        return 1;
    }

while(in>>temp) {
        datay.push_back(temp);
    }

std::vector<std::pair<double, double> > data;

for(std::vector<double>::const_iterator iterx=datax.begin(),itery=datay.begin();iterx!=datax.end(),itery!=datay.end();iterx++,itery++) {
        data.push_back(std::pair<double,double>(*iterx,*itery));
    }
    in.close();
    double slope=0.0;
    double y_intercept=0.0;
    GetLinearFit(data.begin(),data.end(),slope,y_intercept);
    std::cout<<"最小二乘法得到的结果:"<<std::endl;
    std::cout<<"slope: "<<slope<<std::endl;
    std::cout<<"y_intercept: "<<y_intercept<<std::endl;

slope=1.0,y_intercept=1.0;
    BatchGradientDescent(data.begin(),data.end(),slope,y_intercept);
    std::cout<<"批量梯度下降法得到的结果:"<<std::endl;
    std::cout<<"slope: "<<slope<<std::endl;
    std::cout<<"y_intercept: "<<y_intercept<<std::endl;

slope=1.0,y_intercept=1.0;
    StochasticGradientDescent(data.begin(),data.end(),slope,y_intercept);
    std::cout<<"随机梯度下降法得到的结果:"<<std::endl;
    std::cout<<"slope: "<<slope<<std::endl;
    std::cout<<"y_intercept: "<<y_intercept<<std::endl;

slope=1.0,y_intercept=1.0;
 LWR(data.begin(),data.end(),slope,y_intercept);
 std::cout<<"locally weighted linear regression 得到的结果:"<<std::endl;
 std::cout<<"slope: "<<slope<<std::endl;
 std::cout<<"y_intercept: "<<y_intercept<<std::endl;

return 0;
}

线性回归(最小二乘法、批量梯度下降法、随机梯度下降法、局部加权线性回归) C++的更多相关文章

  1. Locally Weighted Linear Regression 局部加权线性回归-R实现

      局部加权线性回归  [转载时请注明来源]:http://www.cnblogs.com/runner-ljt/ Ljt 作为一个初学者,水平有限,欢迎交流指正. 线性回归容易出现过拟合或欠拟合的问 ...

  2. Locally weighted linear regression(局部加权线性回归)

    (整理自AndrewNG的课件,转载请注明.整理者:华科小涛@http://www.cnblogs.com/hust-ghtao/) 前面几篇博客主要介绍了线性回归的学习算法,那么它有什么不足的地方么 ...

  3. 局部加权线性回归(Locally weighted linear regression)

    首先我们来看一个线性回归的问题,在下面的例子中,我们选取不同维度的特征来对我们的数据进行拟合. 对于上面三个图像做如下解释: 选取一个特征,来拟合数据,可以看出来拟合情况并不是很好,有些数据误差还是比 ...

  4. 梯度下降&随机梯度下降&批梯度下降

    梯度下降法 ​ 下面的h(x)是要拟合的函数,J(θ)损失函数,theta是参数,要迭代求解的值,theta求解出来了那最终要拟合的函数h(θ)就出来了.其中m是训练集的记录条数,j是参数的个数. 梯 ...

  5. matlab练习程序(局部加权线性回归)

    通常我们使用的最小二乘都需要预先设定一个模型,然后通过最小二乘方法解出模型的系数. 而大多数情况是我们是不知道这个模型的,比如这篇博客中z=ax^2+by^2+cxy+dx+ey+f 这样的模型. 局 ...

  6. sklearn中实现随机梯度下降法(多元线性回归)

    sklearn中实现随机梯度下降法 随机梯度下降法是一种根据模拟退火的原理对损失函数进行最小化的一种计算方式,在sklearn中主要用于多元线性回归算法中,是一种比较高效的最优化方法,其中的梯度下降系 ...

  7. NN优化方法对照:梯度下降、随机梯度下降和批量梯度下降

    1.前言 这几种方法呢都是在求最优解中常常出现的方法,主要是应用迭代的思想来逼近.在梯度下降算法中.都是环绕下面这个式子展开: 当中在上面的式子中hθ(x)代表.输入为x的时候的其当时θ參数下的输出值 ...

  8. L20 梯度下降、随机梯度下降和小批量梯度下降

    airfoil4755 下载 链接:https://pan.baidu.com/s/1YEtNjJ0_G9eeH6A6vHXhnA 提取码:dwjq 梯度下降 (Boyd & Vandenbe ...

  9. 监督学习:随机梯度下降算法(sgd)和批梯度下降算法(bgd)

    线性回归 首先要明白什么是回归.回归的目的是通过几个已知数据来预测另一个数值型数据的目标值. 假设特征和结果满足线性关系,即满足一个计算公式h(x),这个公式的自变量就是已知的数据x,函数值h(x)就 ...

随机推荐

  1. java攻城狮之路--复习JDBC(PrepareStatement)

    PreparedStatement: 1.可以通过调用 Connection 对象的 preparedStatement() 方法获取 PreparedStatement 对象 2.PreparedS ...

  2. PHP递归复制文件夹以及传输文件夹到其他服务器。

    项目中需要复制整个文件夹,有时候还需要将整个文件夹传输到远程服务器. 这里就要递归遍历整个文件夹了,想看递归遍历文件夹的代码. function deepScanDir($dir) { $fileAr ...

  3. JpGraph 画图

    1:借鉴地址 PHP jpgraph安装及基本用法 http://www.php.cn/php-weizijiaocheng-400977.html JpGraph使用详解之中文乱码解决方法 http ...

  4. 彩色MT9V034摄像头 Bayer转rgb FPGA实现

    1 图像bayer格式介绍 bayer格式是伊士曼·柯达公司科学家Bryce Bayer发明的,Bryce Bayer所发明的拜耳阵列被广泛运用数字图像.Bayer格式是相机内部的原始数据, 一般后缀 ...

  5. sublime text3 verilog代码编写高级操作篇

    2018.10.21 好久没写博客了,这段时间一直在学习一直在沉淀,然而发现学的越多会的更少,只能快马加鞭吧! 博主从大一暑假接触FPGA,到现在快一年半了,时间恍逝.刚开始入门也是用的quartus ...

  6. join 和 left join 和 right join的区别?

    join等价于 inner join 是内连接 ,返回两个表都有的符合条件的行. left join 是左连接,返回坐表中所有的行以及右表中符合条件的行. right join右连接,是返回右表中所有 ...

  7. uva 1587(Box UVA - 1587)

    题目大意是给定6个数对,每个数对代表一个面的长和宽,判断这6个面是否能构成一个长方体. 这种题一看很复杂,但是只要不想多了实际上这就是一个水题... 首先说明一下判断的思路: 1.长方体是有三个对面的 ...

  8. JavaScript控制iframe中元素的样式

    //根据ID获取要操控元素 var deptObjs=document.getElementById("IFRAMEID").contentWindow.document.getE ...

  9. 第一节:初识pandas之Series(上)

    Series线性的数据结构, 也是一个一维数组. 声明:本人Python小白,以下代码只是个人学习的过程,仅仅记录一下学习的点点滴滴,若有错误,还望指正. (注:该代码均在jupyter notebo ...

  10. ZooKeeper学习总结(1)——ZooKeeper入门介绍

    1. 概述 Zookeeper是Hadoop的一个子项目,它是分布式系统中的协调系统,可提供的服务主要有:配置服务.名字服务.分布式同步.组服务等. 它有如下的一些特点: 简单 Zookeeper的核 ...