机器学习基石PLA算法c++语言实现

其中的Item.label为数据中的判断结果,例如在授予信用卡的时候为 是 或者 否,其算法的目的就在于确定其中wight中个分量的值
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

struct Item{
    int x0 = 1; //需要C++11
    double x1, x2, x3, x4;
    int label;
};

struct Wight{
    double w0, w1, w2, w3, w4;
}Wit0 = { 0, 0, 0, 0, 0 };

//
int sign(double x){
    if (x>0)
        return 1;
    else if (x<0)
        return -1;
    else
        return 0;
}

//
double DotPro(Item item, Wight wit){
    return item.x0*wit.w0 + item.x1*wit.w1 + item.x2*wit.w2 + item.x3*wit.w3 + item.x4*wit.w4;
}

//
Item NumPro(int k, Item item){
    Item NewItem;
    NewItem.x0 = item.x0*k;
    NewItem.x1 = item.x1*k;
    NewItem.x2 = item.x2*k;
    NewItem.x3 = item.x3*k;
    NewItem.x4 = item.x4*k;
    return NewItem;
}

//
Wight WightAnd(Item item, Wight wit){
    Wight NewWigth;
    NewWigth.w0 = item.x0 + wit.w0;
    NewWigth.w1 = item.x1 + wit.w1;
    NewWigth.w2 = item.x2 + wit.w2;
    NewWigth.w3 = item.x3 + wit.w3;
    NewWigth.w4 = item.x4 + wit.w4;
    return NewWigth;
}

//
void main()
{
    ofstream output("D:/data2.txt");
    ifstream input("D:/data0.txt");
    vector<Item> data;
    Item temp;
    while (input >> temp.x1 >> temp.x2 >> temp.x3 >> temp.x4 >> temp.label){
        data.push_back(temp);
    }

    vector<Item>::iterator it;
    Wight wit = Wit0;
    for (it = data.begin(); it != data.end(); it++)
    {
        if ((*it).label != sign(DotPro(*it, wit))){
            wit = WightAnd(NumPro((*it).label, *it), wit);
            it = data.begin();
        }
    }
    cout << wit.w0 << " " << wit.w1 << " " << wit.w2 << " " << wit.w3 << " " << wit.w4 << endl;

    /* 测试数据
    for (it = data.begin(); it != data.end(); it++)
    {
        output << sign(DotPro(*it, wit)) << endl;
    }
    */
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值