We can estimate the weight values for our training data using stochastic gradient descent.

Stochastic gradient descent requires two parameters:

  • Learning Rate: Used to limit the amount each weight is corrected each time it is updated.
  • Epochs: The number of times to run through the training data while updating the weight.

These, along with the training data will be the arguments to the function.

There are 3 loops we need to perform in the function:

  1. Loop over each epoch.
  2. Loop over each row in the training data for an epoch.
  3. Loop over each weight and update it for a row in an epoch.

As you can see, we update each weight for each row in the training data, each epoch.

The loop is over until:

  the iteration error is less than a user-specified error threshold or

  a predetermined number of iterations have been completed.

Weights are updated based on the error the model made. The error is calculated as the difference between the expected output value and the prediction made with the candidate weights.

Notice that learning only occurs when an error is made, otherwise the weights are left unchanged.

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

//the sign function
template <typename DataType, typename WeightType>
double sign(typename::std::vector<DataType> &data, typename::std::vector<WeightType> &weights) {
    double result=0.0;

for(size_t i=0; i<weights.size(); ++i) {
        result += data.at(i)*weights.at(i);
    }

if(result >= 0.0)
        return 1.0;
    else
        return 0.0;
}

template <typename DataType, typename WeightType>
void trainW(typename::std::vector<std::vector<DataType> > &vv, typename::std::vector<WeightType> &weights, const double& l_rate, const int& n_epoch) {
    std::vector<DataType> v_data;

for(size_t i=0; i<weights.size(); ++i) {
        weights.at(i)=0.0;
    }

for(size_t i=0; i<n_epoch; ++i) {
        double sum_error=0.0;

for(size_t j=0; j<vv.size(); ++j) {
            v_data.clear();
            for(size_t k=0; k<weights.size(); ++k) {
                v_data.push_back(vv[j][k]);
            }

for(typename::std::vector<DataType>::iterator it=v_data.begin();it!=v_data.end();++it) {
                std::cout<<*it<<" ";
            }

std::cout<<std::endl;

            double prediction=sign(v_data, weights);
            double error=vv[j].back()-prediction;
            std::cout<<"expected: "<<vv[j].back()<<" prediction: "<<prediction<<" error: "<<error<<std::endl;

sum_error+=pow(error, 2.0);

for(size_t k=0; k<weights.size(); ++k) {
                weights.at(k)=weights.at(k)+l_rate*error*vv[j][k];
            }
        }
        std::cout<<"epoch = "<<i<<" error = "<<sum_error<<std::endl;
    }

for(size_t i=0; i<weights.size(); ++i) {
        std::cout<<weights.at(i)<<" ";
    }
    std::cout<<std::endl;
}

//make a prediction with weights, appended to the last column
template <typename DataType, typename WeightType>
void predictTestData(typename::std::vector<std::vector<DataType> > &vv, typename::std::vector<WeightType> &weights) {
    std::vector<DataType> v_data;

for(size_t i=0;i<vv.size();++i) {
        v_data.clear();
        for(size_t j=0;j<weights.size();++j) {
            v_data.push_back(vv[i][j]);
        }

double signResult=sign(v_data,weights);
        vv[i].push_back(signResult);
    }
}

//display the data
template <typename DataType>
void DisplayData(typename::std::vector<std::vector<DataType> > &vv) {
    std::cout<<"the number of data: "<<vv.size()<<std::endl;

for(size_t i=0; i<vv.size(); ++i) {
        for(typename::std::vector<DataType>::iterator it=vv[i].begin(); it!=vv[i].end(); ++it) {
            std::cout<<*it<<" ";
        }
        std::cout<<std::endl;
    }
}

int main() {
    std::ifstream infile_feat("PLA.txt");
    std::string feature;
    float feat_onePoint;
    std::vector<float> lines;
    std::vector<std::vector<float> > lines_feat;
    lines_feat.clear();

std::vector<float> v_weights;
    v_weights.clear();
    v_weights.push_back(-0.1);
    v_weights.push_back(0.206);
    v_weights.push_back(-0.234);

while(!infile_feat.eof()) {
        getline(infile_feat, feature);
            if(feature.empty())
                break;
        std::stringstream stringin(feature);
        lines.clear();

lines.push_back(1);
        while(stringin >> feat_onePoint) {
            lines.push_back(feat_onePoint);
        }
        lines_feat.push_back(lines);
    }

infile_feat.close();

std::cout<<"display train data: "<<std::endl;

DisplayData(lines_feat);

double l_rate=0.1;

int n_epoch=5;

trainW(lines_feat, v_weights, l_rate, n_epoch);

//predictTestData(lines_feat, v_weights);

//std::cout<<"the predicted: "<<std::endl;
    //DisplayData(lines_feat);

return 0;
}

感知器算法 C++的更多相关文章

  1. Stanford大学机器学习公开课(三):局部加权回归、最小二乘的概率解释、逻辑回归、感知器算法

    (一)局部加权回归 通常情况下的线性拟合不能很好地预测所有的值,因为它容易导致欠拟合(under fitting).如下图的左图.而多项式拟合能拟合所有数据,但是在预测新样本的时候又会变得很糟糕,因为 ...

  2. 第三集 欠拟合与过拟合的概念、局部加权回归、logistic回归、感知器算法

    课程大纲 欠拟合的概念(非正式):数据中某些非常明显的模式没有成功的被拟合出来.如图所示,更适合这组数据的应该是而不是一条直线. 过拟合的概念(非正式):算法拟合出的结果仅仅反映了所给的特定数据的特质 ...

  3. [置顶] 局部加权回归、最小二乘的概率解释、逻辑斯蒂回归、感知器算法——斯坦福ML公开课笔记3

    转载请注明:http://blog.csdn.net/xinzhangyanxiang/article/details/9113681 最近在看Ng的机器学习公开课,Ng的讲法循循善诱,感觉提高了不少 ...

  4. 感知器算法--python实现

    写在前面: 参考: 1  <统计学习方法>第二章感知机[感知机的概念.误分类的判断]   http://pan.baidu.com/s/1hrTscza 2   点到面的距离 3   梯度 ...

  5. Perceptron Algorithm 感知器算法及其实现

    Rosenblatt于1958年发布的感知器算法,算是机器学习鼻祖级别的算法.其算法着眼于最简单的情况,即使用单个神经元.单层网络进行监督学习(目标结果已知),并且输入数据线性可分.我们可以用该算法来 ...

  6. 机器学习之感知器算法原理和Python实现

    (1)感知器模型 感知器模型包含多个输入节点:X0-Xn,权重矩阵W0-Wn(其中X0和W0代表的偏置因子,一般X0=1,图中X0处应该是Xn)一个输出节点O,激活函数是sign函数. (2)感知器学 ...

  7. 【2008nmj】Logistic回归二元分类感知器算法.docx

    给你一堆样本数据(xi,yi),并标上标签[0,1],让你建立模型(分类感知器二元),对于新给的测试数据进行分类. 要将两种数据分开,这是一个分类问题,建立数学模型,(x,y,z),z指示[0,1], ...

  8. 感知器算法PLA

    for batch&supervised binary classfication,g≈f <=> Eout(g)≥0 achieved through Eout(g)≈Ein(g ...

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

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

随机推荐

  1. JS——math

    random() 方法可返回介于 0 ~ 1 之间的一个随机数. Math.random() 0.0 ~ 1.0 之间的一个伪随机数,但是不包括0和1.

  2. CSS——float

    float:就是在于布局,首先要介绍的是文档流(标准流),之后是浮动布局. 文档流:元素自上而下,自左而右,块元素独占一行,行内元素在一行上显示,碰到父集元素的边框换行. 浮动布局: 1.float: ...

  3. Python 时间处理---------笔记

    时区处理&格式化 import pytz from datetime import datetime # 设置时区 timezone = pytz.timezone('Asia/Shangha ...

  4. Oracle Sequence不设置cache参数的几个潜在问题(转载)

    转载于 http://www.uml.org.cn/sjjm/201204065.asp 在Oracle中,我们没有MYSQL和SQL                           Server ...

  5. 用最简单的脚本完成supertab的基本功能并实现一个更加合理的功能

    supertab是vim的一个出名的插件, 相信会vim的人没几个不知道的, 我在之前的<<vim之补全1>>中首先说明的也是它, supertab实现的功能简单的说就是用ta ...

  6. VHDL之Serial-Parallel Multiplier

    1 Serial-parallel multiplier Figure 12.1 shows the RTL diagram of a serial-parallel multiplier. One ...

  7. Mongo优化笔记

    最近MongoDb服务器负载比较高,容易出问题,这里把优化的方式整理一下. 1.由于各个项目组共用一个mongo实例,所以一个项目组的问题会影响到别的项目组,所以需要把各个项目的数据从一个实例中剥离出 ...

  8. SPPNet论文翻译-空间金字塔池化Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition

    http://www.dengfanxin.cn/?p=403 原文地址 我对物体检测的一篇重要著作SPPNet的论文的主要部分进行了翻译工作.SPPNet的初衷非常明晰,就是希望网络对输入的尺寸更加 ...

  9. 【sqli-labs】 less49 GET -Error based -String -Blind -Order By Clause(GET型基于盲注的字符型Order By从句注入)

    都是order by的注入,作者连图片都懒得改了... 注意和整型的区别,前引号用提交的引号闭合,后引号用#注释 http://192.168.136.128/sqli-labs-master/Les ...

  10. mstsc windows7/10远程桌面身份验证错误 要求的函数不受支持

    之前好好的能远程桌面连接到服务器,但是今天来就不能连接上了,并提示:身份验证错误.要求的函数不受支持. 猜想可能是Windows又更新了什么鬼,后面查询资料知道是由于CredSSP加密Oracle修正 ...