您的位置:首页 > 编程语言 > C语言/C++

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

2015-07-21 22:32 621 查看
其中的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;
}
*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: