C++实现感知机算法

感知机是用来分类的模型,f(x)表示由输入空间的到输出空间的函数

 

f(x)=sign(wx+b)


感知机学习策略

学习策略主要为梯度下降法,以误分类点到超平面的距离作为损失函数,通过优化损失函数到最小得到最优的区分超平面。

算法流程如图所示:

 代码实现

原始形式(对偶形式修改条件继续循环即可):

#pragma once
#include <iostream>
#include <fstream>
#include<Eigen/Dense>
#include <algorithm>
#include <vector>



//import data
void ImportPointCloud(char& filename, std::vector<Eigen::RowVector3d>& points)
{
    Eigen::RowVector3d temp;
    bool mStatus = false;
    std::ifstream import;
    import.open(&filename);
    while (import.peek() != EOF)
    {
        import >> temp(0) >> temp(1) >> temp(2);
        points.push_back(temp);
    }
    import.close();
}


int main()
{
    char filename[255];
    sprintf_s(filename, 255, "perception.txt");
    std::vector<Eigen::RowVector3d> points;
    std::vector<Eigen::RowVector2d> X;
    std::vector<float> Y;
    ImportPointCloud(*filename, points);

    //classified data and result
    for (int i = 0; i < points.size(); i++)
    {
        Eigen::RowVector2d temp_X;
        float temp_Y;
        temp_X << points[i](0), points[i](1);
        X.push_back(temp_X);
        temp_Y = points[i](2);
        Y.push_back(temp_Y);
    }

    //start iteration
    Eigen::RowVector2d w;
    w << 0, 0;
    int b = 0, seta = 1;
    bool flag = true;
    int count =0;


    while (flag)
    {

        //one iteration
        for (int i = 0; i < points.size(); i++)
        {
            if (Y[i] * (w.dot(X[i]) + b) <= 0)
            {
                w += seta * Y[i] * X[i];
                b += seta * Y[i];
            }

        }

        //termination condition
        for (int j = 0; j < points.size(); j++)
        {
            if (Y[j] * (w.dot(X[j]) + b) > 0)
            {
                count += 1;
            }
        }
        if (count == points.size()) {

            flag = false;
        }
        count = 0;
        
    }

    std::cout << w<< std::endl;
    std::cout << b << std::endl;
    system("pause");
    return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值