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

机器学习基石——台湾大学 

感知器学习算法(PLA) c++语言实现过程。

 

#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;
    }
    */
}

 

posted @ 2014-04-20 19:42  Beenking  阅读(1184)  评论(0编辑  收藏  举报